Merging multiple lists in 1 list

Viewed 89

This what I have:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

This is what I want:

list4 = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]

How to fix this?

3 Answers

To create a list of lists like this simply use:

list4 = [list1, list2, list3]

You should only simple put the lists to another list: list4 = [list1, list2, list3]. The result will be a 2D list (as you expected).

Complete code:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

list4 = [list1, list2, list3]

print("Result: {}".format(list4))

Output:

>>> python3 test.py
Result: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
res = []
for l in (lis1, list2, list3):
    res.extend(l)

That would give you yet another list, named res that is "flattered" representation of those three sublists.

Related