greedsin
greedsin

Reputation: 1270

Remove None from tuple

previous answers on how to remove None from a list dont help me! I am creating a list of tuples with:

list(zip(*[iter(pointList)] *3))

So what i have is

[(object1,object2,object3),(object4,object5,object6),(object7,None,None)]

or

[(object1,object2,object3),(object4,object5,object6),(object7,object8,None)]

And i want to remove the None in the tuples (which only can occure at the last entry of the list!). So my desired output would be:

[(object1,object2,object3),(object4,object5,object6),(object7)]

or

[(object1,object2,object3),(object4,object5,object6),(object7,object8)]

What i thought would help me is:

filter(None,myList)

Upvotes: 5

Views: 11300

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

Tuples are immutable so once you construct a tuple you cannot alter its length or set its elements. Your only option is thus to construct new tuples as a post processing step, or don't generate these tuples in the first place.

Post processing

Simply use a generator with the tuple(..) constructor in a list comprehension statement:

[tuple(xi for xi in x if xi is not None) for x in data]

Alter the "packing" algorithm

With packing I mean converting a list of m×n items into n "slices" of m elements (which is what your first code fragment does).

If - like the variable name seems to suggest - pointList is a list. You can save yourself the trouble of using zip, and work with:

[tuple(pointList[i:i+3]) for i in range(0,len(pointList),3)]

directly. This will probably be a bit more efficient as well since here we never generate tuples with Nones in the first place (given postList does not contain Nones of course).

Upvotes: 12

Related Questions