Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Python, How to join a list of tuples into one list? [duplicate]

Tags:

python

tuples

Following on my previous question How to group list items into tuple?

If I have a list of tuples, for example

a = [(1,3),(5,4)] 

How can I unpack the tuples and reformat it into one single list

b = [1,3,5,4] 

I think this also has to do with the iter function, but I really don't know how to do this. Please enlighten me.

like image 332
LWZ Avatar asked Mar 07 '13 10:03

LWZ


People also ask

How do you combine lists within a list Python?

📢 TLDR: Use + In almost all simple situations, using list1 + list2 is the way you want to concatenate lists. The edge cases below are better in some situations, but + is generally the best choice. All options covered work in Python 2.3, Python 2.7, and all versions of Python 31.

Can tuples have duplicates Python?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.


2 Answers

b = [i for sub in a for i in sub] 

That will do the trick.

like image 169
Volatility Avatar answered Sep 20 '22 11:09

Volatility


In [11]: list(itertools.chain(*a)) Out[11]: [1, 3, 5, 4] 

If you just need to iterate over 1, 3, 5, 4, you can get rid of the list() call.

like image 29
NPE Avatar answered Sep 23 '22 11:09

NPE