Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from tuple in a list

I've knocking my head against a wall with this:

Basically what I want is to remove " " items from this list of tuples:

[('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]

and obtain the following new list:

[('650', '724', '6354'), ('650', '723', '4539')]

any ideas?

like image 471
Altons Avatar asked Mar 14 '12 01:03

Altons


People also ask

Is it possible to remove element from tuple?

Note: You cannot remove items in a tuple.

How do you remove a value from a tuple in Python?

In Python, we can't delete an item from a tuple. Instead, we have to assign it to a new Tuple. In this example, we used tuple slicing and concatenation to remove the tuple item. The first one, numTuple[:3] + numTuple[4:] removes the third tuple item.

Can you add or remove elements in a tuple in Python?

In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple .

How do I remove a specific element from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.


1 Answers

Tuples in Python are immutable. This means that once you have created a tuple, you can't change the elements contained within it. However, you can create a new tuple that doesn't contain the items you don't want. For example:

>>> a = [('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]
>>> [tuple(y for y in x if y) for x in a]
[('650', '724', '6354'), ('650', '723', '4539')]

This uses a list comprehension [... for x in a] to create a new list using the formula in .... That uses a generator expression y for y in x if y to create a new tuple containing the elements of x only if y is true (meaning the value is truthy, or the string is nonblank).

like image 184
Greg Hewgill Avatar answered Oct 22 '22 00:10

Greg Hewgill