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

How to merge two lists in python

silencement
Release: 2019-06-17 13:20:20
Original
42984 people have browsed it

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)
Copy after login

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]
Copy after login

This is python2 syntax

Method three

Use merge directly

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

Method 4

Use the append method

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

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]]
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template