Reputation: 125
Hello I am trying to merge two lists sequentially into sub lists. I wonder if this is possible without list comprehensions or a lambda operation as I'm still learning how to work with those approaches. Thank you
a = [0,1,2,3]
b = [4,5,6,7]
#desired output
c = [0,4],[1,5],[2,6],[3,7]
Upvotes: 0
Views: 35
Reputation: 3898
Here’s a solution suitable for beginners!
c = []
a = [0,1,2,3]
b = [4,5,6,7]
for i in range(min(len(a), len(b))):
c.append([a[i], b[i]]) # writing [a[i], b[i]] creates a new list
print(c)
Upvotes: 0
Reputation: 160577
An approach that doesn't involve lambda
s or list comprehensions (not sure what the issue is with list-comps) would be with map
:
c = list(map(list, zip(a, b)))
This first zip
s the lists together, then creates a list
instance for every tuple generated from zip
with map
and wraps it all up in list
in order for map
to yield all it's contents:
print(c)
[[0, 4], [1, 5], [2, 6], [3, 7]]
This, at least in my view, is less understandable than the equivalent comprehension John supplied in a comment.
Upvotes: 1