“This is the fifth day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

Runtime environment

Python: 3.8.3 jupyter-notebook: 6.4.0

Note: This example can be run directly on jupyter-Notebook, but PyCharm requires print at the end of the code.


The list of operations

list()

List () turns an iterable into a list.

Sample 🅰 ️

list((0.1.2)) + list({0.1.2}) + list('012')
Copy the code
Output: [0, 1, 2, 0, 1, 2, ‘0’, ‘1’, ‘2’]
Converts tuples, sets, and strings to lists and concatenates them with operators.


Sample 🅱 ️

list(range(3))
Copy the code
Output: [0, 1, 2]
Convert an iterable to a list


list.append()

lst = ['Python'.'Java']
lst.append('C')
lst
Copy the code
Output: [‘Python’, ‘Java’, ‘C’]


list.extend()

Extend () extends the list by adding elements from iterables (lists, tuples, dictionaries, strings) to the end of the list.

1️ additional list

lst = ['Python'.'Java'.'C']
lst.extend([1.2.3])
lst
Copy the code
Output: [‘Python’, ‘Java’, ‘C’, 1, 2, 3]


2️ append string

lst = ['Python'.'Java'.'C']
lst.extend('123')
lst
Copy the code
Output: [‘Python’, ‘Java’, ‘C’, ‘1’, ‘2’, ‘3’]
Appends each character in the string as an element to the end of the original list


3️ additional collection

lst = ['Python'.'Java'.'C']
lst.extend({1.2.3})
lst
Copy the code
Output: [‘Python’, ‘Java’, ‘C’, 1, 2, 3]


4️ additional dictionary

lst = ['Python'.'Java'.'C']
lst.extend({1: 'b'.2: 'a'})
lst
Copy the code
Output: [‘Python’, ‘Java’, ‘C’, 1, 2]
Append only the dictionary key to the end of the original list


list.insert()

Insert (index, object) Inserts the specified object into the index position of the list.

Sample 🅰 ️

lst = ['Python'.'Java'.'C']
lst.insert(1.'C++')
lst
Copy the code
Output: [‘Python’, ‘C++’, ‘Java’, ‘C’]


Sample 🅱 ️

lst = ['Python'.'Java'.'C']
lst.insert(6.'C++')
lst
Copy the code
Output: [‘Python’, ‘Java’, ‘C’, ‘C++’]
whenindexIs added to the end of the list if the value of.


list.pop()

Pop (index=-1) removes the element at the specified position in the list (the last one by default) and returns the value of the removed element. An error is reported if the specified index exceeds the list length.

lst = ['Python'.'Java'.'C']
lst.pop(1), lst
Copy the code
Output :(‘Java’, [‘Python’, ‘C’])


List. Remove (elements)

Lst.remove (value) Removes the value that appears for the first time in the list. If value is not in the list, an error is reported.

Sample 🅰 ️

lst = ['Python'.'Java'.'C'.'Python']
lst.remove('Python')
lst
Copy the code
Output: [‘Java’, ‘C’, ‘Python’]
Delete only the first occurrencePython


Sample 🅱 ️

lst = ['Python'.'Java'.'C'.'Python']
lst.remove('HTML')
lst
Copy the code
Output: ValueError: list.remove(x): x not in list
HTMLNot in the list, error occurred


list.clear()

List.clear () removes all elements in the list, with no return value.

lst = ['Python'.'Java'.'C']
lst.clear()
lst
Copy the code
Output: []


list.index()

Index (value, start, stop) returns the index of the first element found in the list that matches value. The scope of the search can be specified by [start, stop).

Sample 🅰 ️

lst = ['Python'.'Java'.'C'.'Python'.'Python']
lst.index('Python')
Copy the code
Output: 0
Searches all elements of the list without specifying a range


Sample 🅱 ️

lst = ['Python'.'Java'.'C'.'Python'.'Python']
lst.index('Python'.1.3)
Copy the code
Output: ValueError: ‘Python’ is not in list
Specify the range [1, 3], that is, look in [‘Java’, ‘C’]PythonObviously not present, error reported


list.count()

Count (value) Returns the number of occurrences of value in the list. Returns 0 if no value is found in the list.

Sample 🅰 ️

lst = ['Python'.'Java'.'C'.'Python'.'Python']
lst.count('Python')
Copy the code
Output: 3


Sample 🅱 ️

lst = ['Python'.'Java'.'C'.'Python'.'Python']
lst.count('Py')
Copy the code
Output: 0
There are no elements in the list'Py', returns 0.


list.reverse()

Reverse () sorts the list in reverse order, with no return value.

lst = [1.5.9.2]
lst.reverse()
lst
Copy the code
Output: [2, 9, 5, 1]


list.sort()

Sort () sorts the list in a specified way, modifying the original list, which is stable (that is, the order of two equal elements does not change because of sorting).

  • Key: Specifies that each element in the iterable is sorted according to this function
  • Reverse: FalseAs an ascending,TrueIn descending order.

Sample 🅰 ️

lst = [1.5.9.2]
lst.sort()
lst
Copy the code
Output: [1, 2, 5, 9]


Sample 🅱 ️

lst = ['Python'.'C'.'Java'] 
lst.sort(key=lambda x:len(x), reverse=False)
lst
Copy the code
Output: [‘C’, ‘Java’, ‘Python’]
The specifiedkeyCalculates the length of each element in the list and sorts it in ascending order by length


list.copy()

Copy () makes a copy of the list and returns the newly generated list. This copy is a shallow copy, and we’ll explain why it’s a shallow copy.

Sample 🅰 ️

lst = [[1.2.3].'a' ,'b']
lst_copy = lst.copy()
lst_copy.pop()
lst, lst_copy
Copy the code
Output :([[1, 2, 3], ‘a’, ‘b’], [[1, 2, 3], ‘a’])
rightlstforcopyAnd then delete the listlst_copyThe last element of thelstThe last element of the list is not deleted, indicating that the two lists do point to different addresses.


Sample 🅱 ️

lst = [[1.2.3].'a' ,'b']
lst_copy = lst.copy()
lst_copy[0].pop()
lst_copy.pop()
lst, lst_copy
Copy the code
Output ([[1, 2], ‘a’, ‘b’], [[1, 2], ‘A ‘, ‘b’]) output ([[1, 2], ‘a’, ‘b’])
Here we do the same thing as in the previous example, except this time we delete one more element, the last element in the nested sublist of the list, and observe that it’s not justlst_copyThe list changes to the original listlstThe nested word list in the. Note The two lists point to different addresses, but the sub-lists point to the same address.


Extension: direct assignment, shallow copy, deep copy

(1) Direct assignment, passing a reference to the object. If the original list changes, the assigned object does the same.

(2) Shallow copy, no child object is copied, so the original data child object changes, copied child object will also change.

(3) Deep copy, contains the copy of the child object inside the object, so the change of the original object will not cause the change of any child elements in the deep copy, the two are completely independent.

1️ first look at direct assignment

lst = [1.2.3[1.2]]
list1 = lst

# -- Directly assign --
lst.append('a')
list1[3].append('b')

print(lst,'address:.id(lst))   
print(list1,'address:.id(list1))
# [1, 2, 3, [1, 2, 'b'], 'a'] address
# [1, 2, 3, [1, 2, 'b'], 'a'] address
Copy the code

Whether LST or LIST1 changes, both will be affected.


2️ superficial copy needs copy module, or list.copy() has the same effect

from copy import copy

lst = [1.2.3[1.2]]
list2 = copy(lst)

# shallow copy
lst.append('a')
list2[3].append('b')

print(lst,'address:.id(lst))
print(list2,'address:.id(list2))
# [1, 2, 3, [1, 2, 'b'], 'a'
# [1, 2, 3, [1, 2, 'b'] address: 2112495897728
Copy the code

The LST address is different from the LIST2 address, but the address of the sublist is still the same, and both are affected when an element in the sublist is modified.


3️ deepcopy needs deepcopy in copy module, at this time the two lists are completely independent.

from copy import deepcopy

lst = [1.2.3[1.2]]
list3 = deepcopy(lst)

# -- deep copy --
lst.append('a')
list3[3].append('b')

print(lst,'address:.id(lst))
print(list3,'address:.id(list3))
# [1, 2, 3, [1, 2], 'a'] address: 2112506144192
# [1, 2, 3, [1, 2, 'b'] address: 2112499460224
Copy the code

Based on the results, you can see that when you change the values in the sublist, the original list does not change.



That’s all for this article, if it feels good.❤ Just like it before you go!! ❤

For those who are new to Python or want to learn Python, you can search “Python New Horizons” on wechat to communicate and learn with others. They are all beginners. Sometimes a simple question is stuck for a long time, but others may suddenly realize it with a little help.