Based on the number of time the for loop runs, I get multiple list. I want to merge all those list and make one list.
for example:
list = []
for i in item:
list.append(i)
print(list)
How can I merge all the list I get to one list ?
CodePudding user response:
If your item is list of lists, then you can use extend
to achieve the same.
lst = []
for i in item:
lst.append(i)
out = []
for sublist in lst:
out.extend(sublist)
print(out)
Also, avoid using python keywords like list
for the variable name, use something like lst instead.
CodePudding user response:
list1 = ["hey"]
list2 = ["yo"]
list1.append(list2) = ["hey", ["yo"]]
list1.extend(list2) = ["hey", "yo"]
list1 = list list2 = ["hey", "yo"]
CodePudding user response:
You should avoid using list
as a variable name, it's a reserved word for python lists.
This code should work for you:
list_ = []
f_list = []
item = [1,2,3,4,5]
for i in item:
list_.append(i)
f_list.extend(list_)
print(list_)
print("Final list - ", f_list)
Output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Final list - [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]