I have 3 lists:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
And I need to write a function that will return this list: [1, 4, 7, 2, 5, 8, 3 ,6 ,9] How can I do that?
I have 3 lists:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
And I need to write a function that will return this list: [1, 4, 7, 2, 5, 8, 3 ,6 ,9] How can I do that?
# Your lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
new_list = [list1, list2, list3]
new_list = list(map(list, zip(*new_list)))
print(sum(new_list,[])) # Output: [1, 4, 7, 2, 5, 8, 3 ,6 ,9]
Expalnation:
Map:
The map()
function is used to apply a function on all elements of a specified iterable and return a map object (We can iterate over its elements).
map()
will take 2 required positional arguments... A function to run against the iterables. and an iterable. ()
Zip:
The zip()
function combines elements of 2 lists with matching indexes into tuples.
zip()
will take an undefined number of arguments where each argument is an iterable to zip.
The * in the zip()
function call "unpacks" a list (or other iterable), making each of its elements a separate argument.
So basically this is what happens:
You have a list of lists [[1,2,3], [4,5,6], [7,8,9]]
The zip(*...)
function will make it be ([1,2,3], [4,5,6], [7,8,9])
Then the map()
function will get inside of it and will get every first element in each list. so it will go over the first list pick up the number 1 and put it in a list, then it will go to the next list and pick up the number 4 and put it in the list, then it will go to the next list and pick up the number 7 and put it in the list. then it will do it again but this time pick the second element from each list.. [2,5,8]
and so on...
then it puts each of those lists it created inside a list [[1, 4, 7, 2, 5, 8, 3 ,6 ,9]]
Finally, to unnest the nested list we use the sum()
function
Hope this helps :)
you can do something like this:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
final_list = []
for i in range(len(list1)):
final_list.append(list1[i])
final_list.append(list2[i])
final_list.append(list3[i])
print(final_list)
this solution works if the lists have the same size. You make a for loop which allows you to browse every elements in every list. After that, you just append the elements of each list to the end of you final list