How to merge two lists in python

coldplay.xixi
Release: 2023-01-03 09:31:11
Original
38230 people have browsed it

How to merge two lists in python: 1. Take out all the elements from the two lists and put them into the new list; 2. Use a built-in function [zip()] in python.

How to merge two lists in python

The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.

Python's method of merging two lists:

Method 1:

The most original and stupidest method, take out the two lists separately Put all the elements into the new list and it will be OK. 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

The action results are as follows:

[1,2,3,4,5,6]
Copy after login

Method 2:

A built-in function zip() in python is used here, its function starts from the name You can see that it is just packaging several unrelated contents together. Without further ado, let’s 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

Pack it first, then reduce the dimension, it’s that simple. (Actually, it’s not simple at all. You’ll have the urge to hit someone when you see it later)

Method 3:

I’ll go and write until the end that I realize that what I wrote before is all nonsense , why, because python syntax can be achieved in one sentence, I actually struggled with an article here, it is really boring.

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

Related free learning recommendations: python video tutorial

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!