Home >Backend Development >Python Tutorial >How to merge two lists in python

How to merge two lists in python

silencement
silencementOriginal
2019-06-11 14:05:3442990browse

How to merge two lists in python

The method of merging lists in python is as follows:

Method 1

The most original and stupidest method is to Take out all the elements from a list and put them into a new list. The sample code is as follows:

list1 = [1,2,3]
list2 = [4,5,6]
list_new = []
for item in list1:
  list_new.append(item)
for item in list2:
  list_new.append(item)
print(list_new)

Method 2

A built-in function zip() in python is used here. Its function can be seen from the name. To come out is to package several originally unrelated contents together. Look at the code:

a = [1,2,3]
b = [4,5,6]
c = zip(a,b) //c = [(1,4),(2,5),(3,6)]
list_new = [row[i] for i in range(len(0)) for row in c]

This is python2 syntax

Method three

Use merge directly

a = [1,2,3]
b = [4,5,6]
c = a + b

Method 4

Use the append method

a = [1,2,3]
b = [4,5,6]
a.append(b)

Note: The append() method adds the b list as a whole to the a list, and the output result is

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


The above is the detailed content of How to merge two lists in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn