Question

I have a list of tuples that look like this;

ListTuple=[('Tuple1', '2ndElement', '3rdElement', 1L), ('Tuple2', '2ndElement', '3rdElement', 2L)]

I want to remove the 2nd element from every tuple inside this list of tuples. The output will look like this;

OutputTuple=[('Tuple1', '3rdElement', 1L), ('Tuple2', '3rdElement', 2L)]

How can this be done in python? Thank you very much.

Was it helpful?

Solution

OutputTuple = [(a, b, d) for a, b, c, d in ListTuple]

Oh and btw, since these are tuples (immutables), you can't "remove" stuff from them. Only create something new.

OTHER TIPS

Keep everything but the second item.

In [4]: [(t[0], t[2], t[3]) for t in ListTuple]
Out[4]: [('Tuple1', '3rdElement', 1L), ('Tuple2', '3rdElement', 2L)]

This solution works without assuming a fixed number of elements in each tuple, or even that there is the same number of elements in each tuple.

ListTuple=[('Tuple1', '2ndElement', '3rdElement', 1L), ('Tuple2', '2ndElement', '3rdElement', 2L)]
output = [((t[0],)+t[2:]) for t in ListTuple]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top