a question about zip...

K

KraftDiner

I had a structure that looked like this
((0,1), (2, 3), (4, 5), (6,7)

I changed my code slightly and now I do this:
odd = (1,3,5,7)
even = (0,2,4,6)
all = zip(even, odd)

however the zip produces:
[(0, 1), (2, 3), (4, 5), (6, 7)]

Which is a list of tuples.. I wanted a tuple of tuples...
 
D

Diez B. Roggisch

KraftDiner said:
I had a structure that looked like this
((0,1), (2, 3), (4, 5), (6,7)

I changed my code slightly and now I do this:
odd = (1,3,5,7)
even = (0,2,4,6)
all = zip(even, odd)

however the zip produces:
[(0, 1), (2, 3), (4, 5), (6, 7)]

Which is a list of tuples.. I wanted a tuple of tuples...

Use tuple(zip(...))

There is a reason that zip returns a list: appending to a list is considered a "natural" operation, whereas extending an
immutable(!) tuple creates a _new_ tuple for each entry. Which is a comparable costly operation - actually quadratic
complexity instead of linear.

So - if you need a tuple afterwards, convert it as shown above.

Diez
 
X

Xavier Morel

KraftDiner said:
I had a structure that looked like this
((0,1), (2, 3), (4, 5), (6,7)

I changed my code slightly and now I do this:
odd = (1,3,5,7)
even = (0,2,4,6)
all = zip(even, odd)

however the zip produces:
[(0, 1), (2, 3), (4, 5), (6, 7)]

Which is a list of tuples.. I wanted a tuple of tuples...
tuple(zip(even, odd))

and if you fear for memory efficiency

tuple(iterator.izip(even, odd))
 
S

Steven D'Aprano

KraftDiner said:
I had a structure that looked like this
((0,1), (2, 3), (4, 5), (6,7)

I changed my code slightly and now I do this:
odd = (1,3,5,7)
even = (0,2,4,6)
all = zip(even, odd)

however the zip produces:
[(0, 1), (2, 3), (4, 5), (6, 7)]

Which is a list of tuples.. I wanted a tuple of tuples...

Others have already told you how to do this. But I have
a question: why do you care that it is a tuple, not a
list? Is there something you need to do with it that
can be done with tuples but not lists?

In other words, while it isn't *wrong* to convert the
list to a tuple, perhaps it is *unnecessary*?
 
S

Steve Holden

KraftDiner said:
I had a structure that looked like this
((0,1), (2, 3), (4, 5), (6,7)

I changed my code slightly and now I do this:
odd = (1,3,5,7)
even = (0,2,4,6)
all = zip(even, odd)

however the zip produces:
[(0, 1), (2, 3), (4, 5), (6, 7)]

Which is a list of tuples.. I wanted a tuple of tuples...
So apply tuple() to the list!

all = tuple(zip(even, odd))

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top