Home > Article > Backend Development > How to merge two lists in python
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.
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
The action results are as follows:
[1,2,3,4,5,6]
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]
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
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!