tumultous_rooster
tumultous_rooster

Reputation: 12550

How can I skip creating tuples with certain values, when using the zip function in Python?

I am using the zip() function in Python.

I am zipping two lists, however, some lists have the value 0 in them. I would like to avoid any tuples with a zero in them.

x = [1, 2, 3]
y = [0, 0, 6]
zipped = zip(x, y)
>>> zipped
[(3, 6)]

In the process of trying to figure this out, I have also come to realize that any possible solution is probably going to be slow, if it involves zipping then removing.

Is there any way to incorporate a condition on zipping? Or should I explore a different, faster method?

Any advice is gratefully appreciated.

Upvotes: 1

Views: 341

Answers (2)

mgilson
mgilson

Reputation: 309919

You could izip and only pass through the proper values:

from itertools import izip
zipped = [(xx, yy) for xx, yy in izip(x, y) if yy]

The reason I choose izip over zip is because in python2.x, zip will generate a new list which really isn't necessary. izip avoids that overhead.

In python3.x, the builtin zip doesn't have this list materializing behavior so you should use that instead. (in fact, itertools.izip doesn't even exist in python3.x)

Upvotes: 2

Paulo Bu
Paulo Bu

Reputation: 29794

zip() by itself won't cover this particular requirement. Nevertheless you can use it along with list comprehensions to get the desired result:

>>>x = [1, 2, 3]
>>>y = [0, 0, 6]
>>>zipped = [(a,b) for a,b in zip(x,y) if a and b]
>>>zipped
[(3,6)]

Regarding to the speed of this method. It will be a lot faster than any new solution you can create yourself using loops, since the looping in this case is performed natively in C which is faster than Python's loops.

Upvotes: 2

Related Questions