Reputation: 1270
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
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.
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]
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 None
s in the first place (given postList
does not contain None
s of course).
Upvotes: 12