[Tutor] Python Idioms?
Alan Gauld
alan.gauld at btinternet.com
Wed Apr 1 11:04:15 CEST 2015
On 01/04/15 05:50, Jim Mooney wrote:
> I'm looking at this and can't see how it works, although I understand
> zipping and unpacking. The docs say it's a Python idiom. Does "idiom" mean
> it works in a special way so I can't figure it out from basic principles?
No idiom means a common pattern of usage in the community.
In this case thats true of zip(), its less true of this
case which is somewhat obscure.
> It looks to me like the iterator in the list gets doubled, so the zip
> should make it [(1,1),(2,2),(3,3),... ], not [(1,2),(3,4),...]
>
> What am I missing here?
The fact that thew list contains a reference to an iterator
so when you multiply by two you get two references
to *the same* iterator.
So each time the iterator gets accessed it returns the next
number in the sequence, not the same number twice.
>>>> s = [1,2,3,4,5,6,7,8]
>>>> list(zip(*[iter(s)]*2))
>>>> [(1, 2), (3, 4), (5, 6), (7, 8)]
Personally I'd have used slicing in this example:
zip(s[::2],s[1::2])
Is that any clearer?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list