Home >Backend Development >Python Tutorial >How to merge two lists in Python
Python method to merge two lists: 1. Use append() to append a list element to the end of the list; 2. Use extend() to append a list to the end of the list; 3. Use "=" to append to the original list A new element; 4. Use a for loop to take out all the elements from the two lists and put them into the new list; 5. Use zip().
Python method to merge two lists
1.append() Appends a new element to the end of the list, The list only occupies one index position, add
to the original list. 2.extend() appends a list to the end of the list, appends each element in the list, and adds
# to the original list. ##3. Using the number directly seems to have the same effect as using extend(), but it actually generates a new list to store the sum of the two lists, and can only be used to add the two lists4. = The effect is the same as extend(), append a new element to the original list, and add to the original list. The code example is as follows 5, Take out all the elements from the two lists respectively, and then put them into the new listlist1 = [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_new6, zip(), package several unrelated contents together
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]Package first, Then reduce the dimension, it’s that simple. (Actually, it’s not simple at all. When you see the back, you will have the urge to hit someone)
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!