Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 740
greedsin Avatar asked Apr 13 '17 14:04

greedsin


People also ask

How do you remove Blank values from a tuple?

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.

How do I get rid of none in Python?

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.

How do I get rid of 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.

Can you remove an item from a tuple?

Note: You cannot remove items in a tuple.


1 Answers

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).

like image 87
Willem Van Onsem Avatar answered Sep 25 '22 03:09

Willem Van Onsem