concat two lists in a list of lists
Question:
Is it possible to concat two lists in a list of lists?
From:
listA = ['a', 'b', 'c']
listB = ['A', 'B', 'C']
listFull = listA + listB
To:
print(listFull)
[['a', 'A'],['b', 'B'],['c', 'C']]
Answers:
"Concatenate" is what the +
does, which puts one list after another. What you’re describing is called a "zip" operation, and Python has exactly that function built-in.
zip
returns an iterable, so if you want a list, you can call list
on it.
print(list(zip(listA, listB)))
# Output: [('a', 'A'), ('b', 'B'), ('c', 'C')]
List comprehension using zip()
listFull = [list(x) for x in zip(listA, listB)]
print(listFull)
You can also use map()
without looping
listFull = list(map(list, zip(listA, listB)))
[['a', 'A'],['b', 'B'],['c', 'C']]
there are several ways to achieve this.
you either need atleast 1 for loop or a map/zip combination.
both possibilities here:
listA = ['a', 'b', 'c']
listB = ['A', 'B', 'C']
#1
listFull =[]
for i in range(len(listA)):
listFull.append([listA[i],listB[i]])
print(listFull)
# output [['a', 'A'], ['b', 'B'], ['c', 'C']]
#2
listfull2 = list(map(list,zip(listA,listB)))
print(listfull2)
# output [['a', 'A'], ['b', 'B'], ['c', 'C']]
Is it possible to concat two lists in a list of lists?
From:
listA = ['a', 'b', 'c']
listB = ['A', 'B', 'C']
listFull = listA + listB
To:
print(listFull)
[['a', 'A'],['b', 'B'],['c', 'C']]
"Concatenate" is what the +
does, which puts one list after another. What you’re describing is called a "zip" operation, and Python has exactly that function built-in.
zip
returns an iterable, so if you want a list, you can call list
on it.
print(list(zip(listA, listB)))
# Output: [('a', 'A'), ('b', 'B'), ('c', 'C')]
List comprehension using zip()
listFull = [list(x) for x in zip(listA, listB)]
print(listFull)
You can also use map()
without looping
listFull = list(map(list, zip(listA, listB)))
[['a', 'A'],['b', 'B'],['c', 'C']]
there are several ways to achieve this.
you either need atleast 1 for loop or a map/zip combination.
both possibilities here:
listA = ['a', 'b', 'c']
listB = ['A', 'B', 'C']
#1
listFull =[]
for i in range(len(listA)):
listFull.append([listA[i],listB[i]])
print(listFull)
# output [['a', 'A'], ['b', 'B'], ['c', 'C']]
#2
listfull2 = list(map(list,zip(listA,listB)))
print(listfull2)
# output [['a', 'A'], ['b', 'B'], ['c', 'C']]