kartoza-geek
kartoza-geek

Reputation: 349

combining list of list to single list Python

I am still learning Python and its terminology so perhaps the way I ask my question is wrong. I have some code that produces results like:

['S 5.3', 0]   
['S 5.4', 10]    
['S 5.5', 20]    

With this I assume this is a list of lists. How can I combine them to have one single list like:

[['S 5.3', 0], ['S 5.4', 10], ['S 5.5', 20]]

Upvotes: 0

Views: 107

Answers (3)

LetzerWille
LetzerWille

Reputation: 5658

look into itertools module 

chain

from itertools import  chain

list1 = ['S 5.3', 0]
list2 = ['S 5.4', 10]
list3 = ['S 5.5', 20]

result = chain(list1, list2, list3)

print(list(result))

['S 5.3', 0, 'S 5.4', 10, 'S 5.5', 20]

Upvotes: 0

jlnabais
jlnabais

Reputation: 819

You should probably take a look at the documentation. This is just an example (I'll let you learn, through the documentation, how to use, for example, the append method in this scenario):

Code:

list1 = ['S 5.3', 0]   
list2 = ['S 5.4', 10]    
list3 = ['S 5.5', 20]  

nested_lists = [list1, list2, list3]
print(nested_lists)

Output:

[['S 5.3', 0],['S 5.4', 10],['S 5.5', 20]]

Upvotes: 3

Muhammad Umar Farooq
Muhammad Umar Farooq

Reputation: 521

Have you looked into append and extend methods

The following example shows the usage of append() method.

aList = [123, 'xyz', 'zara', 'abc'];
aList.append( 2009 );
print "Updated List : ", aList
When we run above program, it produces following result −

Updated List :  [123, 'xyz', 'zara', 'abc', 2009]

The following example shows the usage of extend() method.

aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)

print "Extended List : ", aList 
When we run above program, it produces following result −

Extended List :  [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

Upvotes: 0

Related Questions