Joining Two Lists Together

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]

join list of lists in python

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

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

How do I combine two lists in Dart?

You can use:

var newList = new List.from(list1)..addAll(list2);

If you have several lists you can use:

var newList = [list1, list2, list3].expand((x) => x).toList()

As of Dart 2 you can now use +:

var newList = list1 + list2 + list3;

As of Dart 2.3 you can use the spread operator:

var newList = [...list1, ...list2, ...list3];

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]]

How to combine two lists in R

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

# you can do
c(l1, l2)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with do.call, eg:

do.call(c, list(l1, l2))


Related Topics



Leave a reply



Submit