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)
Method 2: Using the filter() method Using the inbuilt method filter() in Python, we can filter out the empty elements by passing the None as the parameter. This method works in both Python 2 and Python 3 and above, but the desired output is only shown in Python 2 because Python 3 returns a generator.
The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.
The Python filter() function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values.
Note: You cannot remove items in a tuple.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With