Issue
Hi I have three lists like such:
a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
How can I make a new list such that it takes values from all list. For example, it's first three elements will be 1,2,3 as they are the first elements of a,b,c. Therefore, it would look something like
d = [1,2,3,2,3,4,3,4,5,4,5,6]
Solution
You can do that using zip
:
a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
[item for sublist in zip(a, b, c) for item in sublist]
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]
The first for loop:
for sublist in zip(a, b, c)
will iterate on tuples provided by zip
, which will be:
(1st item of a, 1st item of b, 1st item of c)
(2nd item of a, 2nd item of b, 2nd item of c)
...
and the second for loop:
for item in sublist
will iterate on each item of these tuples, building the final list with:
[1st item of a, 1st item of b, 1st item of c, 2nd item of a, 2nd item of b, 2nd item of c ...]
To answer @bjk116's comment, note that the for
loops inside a comprehension are written in the same order that you would use with ordinary imbricated loops:
out = []
for sublist in zip(a, b, c):
for item in sublist:
out.append(item)
print(out)
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]
Answered By - Thierry Lathuille
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.