How to Merge Two Lists into a Single List

How do I merge two lists into a single list?

[j for i in zip(a,b) for j in i]

How do I concatenate two lists in Python?

Use the + operator to combine the lists:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

joinedlist = listone + listtwo

Output:

>>> joinedlist
[1, 2, 3, 4, 5, 6]

How to merge two lists into one list in python

You could use zip and itertools.chain:

from itertools import chain
list(map(list, map(chain.from_iterable, zip(A,B))))

output: [[2, 8], [3, 9], [4, 1], [5, 10], [6, 11]]

join list of lists in python

import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))

This gives

['a', 'b', 'c']

how to merge two lists in python without using plus

+ is adding the lists themselves, you want to apply + to each element.

ops = ['add ', 'subtract ', 'multiply ', 'divide ']
nums = [3, 2, 3, 2]
list3 = [op+str(n) for op, n in zip(ops, nums)]
# or using an fstring to remove "+" entirely
list3 = [f"{op}{n}" for op, n in zip(ops, nums)]

zip lets you iterate multiple "iterables", like lists, in parallel.

edit: changed n to str(n), fstring

Function to combine multiple lists of lists into a single list of lists?

Use unlist, non-recursive on your initial list.

unlist(l, recursive=FALSE)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 4 5 6
#
# [[3]]
# [1] 7 8 9
#
# [[4]]
# [1] 10 11 12
#
# [[5]]
# [1] 13 14 15
#
# [[6]]
# [1] 16 17 18


Related Topics



Leave a reply



Submit