Python List Data Type (list) [Learn Python Essentials] [Read this article is enough]

Your "concern" and "compliment" are trust, recognition, support and motivation...

If you have any comments, you can leave a message.
I will do my best to try to be accurate and comprehensive, and make modifications and supplemental updates throughout my life.

Catalog

1 Python List Data Type Overview

Lists are variable sequences and are often used to store collections of similar items where the exact degree of similarity varies depending on the application.

list data types, represented in Python as lists, can be viewed with the type() function.As follows:

list_demo = ["www.python.org", 'Magnon Ajie', 100.1, [1, 2, 3, 4]]  # Create a list and assign it to the variable list_demo
print(type(list_demo))

Run result:

<class 'list'>

The list encloses all elements in a pair of brackets []. Adjacent elements are separated by commas and element1 ~ elementn denotes the elements in the list. There is no limit to the number of elements, as long as they are Python-supported data types.

Lists can store any type of data, such as integers, decimals (floating point numbers), Booleans, complex numbers, strings, lists, tuples, and so on, and the types of elements in the same list can be different.

Important: To improve the readability of the program, it is not recommended to put different types of data in the same list.

As follows:

[element1, element2, element3, ..., elementn]
["www.python.org", 'Magnon Ajie', 100.1, [1, 2, 3, 4]]

2 Python Create List

2.1 Create lists directly using []

The format is as follows:

listname = [element1 , element2 , element3 , ... , elementn]  # List containing multiple elements
emptylist = []  # A list without any elements, called an empty list

For the above format description:

  • listname: variable name.After you create a list, you usually assign it to a variable to make it easier to call the list.
  • element1 ~ elementn: The element representing the list.

An example of using [] to create a list directly is as follows:

list_demo1 = ['WeChat Public Number:', 'Magnon Ajie']
list_demo2 = ['Blog Park', 'https://www.cnblogs.com/manongajie/']
list_demo3 = ['CSDN Blog', 'https://blog.csdn.net/manongajie']
list_demo4 = ['mailbox', 'manongajie@163.com']
list_demo5 = [7, 4, 5, 9, 9, 1, 7, 4, 1]  # QQ
list_demo6 = []  # Empty List

2.2 Use the list() function to create lists

To create a list using the list() built-in function is to convert other data types into list types.Examples are as follows:

# Convert Strings to Lists
list_demo1 = list('Magnon Ajie')
print(list_demo1)

# Convert tuples to lists
tuple_demo1 = ('python', 'java', 'php', 'c')
list_demo2 = list(tuple_demo1)
print(list_demo2)

# Create an empty list
list_demo3 = list()
print(list_demo3)

Run result:

['code', 'agriculture', 'A', 'Jet']
['python', 'java', 'php', 'c']
[]

3 Access list elements

3.1 Use indexes to access list elements

The format is as follows:

listname[index]

For the above formats,

  • listname: denotes the name of the list.
  • Index: Represents an index value.Python supports both positive and negative indexes.

Examples are as follows:

list_demo4 = ['WeChat Public Number: Nun Ajie', 'Blog Park https://Www.cnblogs.com/manongajie/','CSDN Blog https://blog.csdn.net/manongajie']

print('list_demo4[0] =', list_demo4[0])
print('list_demo4[1] =', list_demo4[1])
print('list_demo4[2] =', list_demo4[2])
print('list_demo4[-1] =', list_demo4[-1])
print('list_demo4[-2] =', list_demo4[-2])
print('list_demo4[-3] =', list_demo4[-3])

Run result:

list_demo4[0] =WeChat Public Number: Number Nong Ajie
 list_demo4[1] =Blog Garden https://www.cnblogs.com/manongajie/
list_demo4[2] = CSDN blog https://blog.csdn.net/manongajie
 list_demo4[-1] = CSDN blog https://blog.csdn.net/manongajie
 list_demo4[-2] =Blog Garden https://www.cnblogs.com/manongajie/
list_demo4[-3] =WeChat Public Number: Number Nong Ajie

3.2 Use slices to access list elements

The format is as follows:

listname[start: end: step]

For the above formats,

  • lsitname: Represents the name of the list.
  • Start: Indicates the start of the index.
  • End: Indicates the end of the index.
  • Step: Represents a step.

The use of each parameter is more flexible, as illustrated below:

list_demo5 = [1, 2, 3, 4, 5, 6]

print('list_demo5[::] =', list_demo5[::])  # None of the three parameters are written
print('list_demo5[:2:2] =', list_demo5[:2:2])  # Do not write the start parameter
print('list_demo5[1::2] =', list_demo5[1::2])  # Do not write end parameters
print('list_demo5[1:2:] =', list_demo5[1:2:])  # Do not write step parameters
print('list_demo5[1:4:2] =', list_demo5[1:4:2])
print('list_demo5[1:4:3] =', list_demo5[1:4:3])
print('list_demo5[1:2] =', list_demo5[1:2])  # Do not step parameters

# Do not step parameters
print('list_demo5[:] =', list_demo5[:])
print('list_demo5[1:] =', list_demo5[1:])
print('list_demo5[2:] =', list_demo5[2:])
print('list_demo5[:1] =', list_demo5[:1])
print('list_demo5[:2] =', list_demo5[:2])
print('list_demo5[1:3] =', list_demo5[1:3])

Run result:

list_demo5[::] = [1, 2, 3, 4, 5, 6]
list_demo5[:2:2] = [1]
list_demo5[1::2] = [2, 4, 6]
list_demo5[1:2:] = [2]
list_demo5[1:4:2] = [2, 4]
list_demo5[1:4:3] = [2]
list_demo5[1:2] = [2]
list_demo5[:] = [1, 2, 3, 4, 5, 6]
list_demo5[1:] = [2, 3, 4, 5, 6]
list_demo5[2:] = [3, 4, 5, 6]
list_demo5[:1] = [1]
list_demo5[:2] = [1, 2]
list_demo5[1:3] = [2, 3]

4 Python Delete List

Python comes with a garbage collection mechanism that automatically recycles a list if it is no longer used.

Of course, you can also delete it manually, so use the del keyword.

Manually deleted formats using the del keyword are as follows:

del listname

For the above formats,

  • listname: The name of the list of corals to be listed.

Examples are as follows:

list_demo6 = [1, 2, 3, 4, 5]
print(list_demo6)
del list_demo6  # Delete list_demo6 using del keyword
print(list_demo6)  # After deletion, print again

Run result:

[1, 2, 3, 4, 5]
Traceback (most recent call last):
  File "D:/Data/PycharmProjects/demo/demo.py", line 68, in <module>
    print(list_demo6)  # After deletion, print again
NameError: name 'list_demo6' is not defined

5 List basic operations (add delete check)

5.1 increase (add list elements)

5.1.1 Python append() method add element

The format is as follows:

listname.append(obj)

For the above formats,

  • The append():append() method adds elements to the list, noting that the element append() adds is at the end of the list.
  • listname: Represents a list of elements to be added.
  • Obj: Represents the data to be added to the end of the list.If obj is a list or tuple, it treats the list or tuple as a whole as an element of the list of elements to be added to form a "new list" containing the list or tuple (the "new list" means that the memory address of the list has not changed and the element has been updated).

Examples are as follows:

Example 1, add data as a string

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
list_demo1.append('Magnon Ajie')  # The data added to the end of list_demo1 with the append() function is a string
print('---- List after adding elements ----: ')
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number',':','Menon Ajie']

Example 2, Add data as a list

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.append([1, 2, 3])  # Use the append() function to add data to the end of list_demo1 as a list
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number',':', [1, 2, 3]]

Example 3, adding data as tuples

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.append((1, 2, 3))  # The data added to the end of list_demo1 with the append() function is a tuple
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number',':', (1, 2, 3)]

5.1.2 Python extend() method add element

The format is as follows:

listname.extend(obj)

For the above formats,

  • Extend():extend() adds elements to the list, noting that the elements added by extend() are at the end of the list.This is consistent with the append() method.
  • listname: The list of elements to be added.
  • Obj:obj represents the data to be added to the end of the list.Note that unlike the append() method, the append() method treats strings, lists, or tuples as a whole as an element of the list of elements to be added, forming a "new list" containing strings, lists, or tuples ("new list" means that the memory address of the list has not changed and the elements have been updated); and the extend() method adds the elements they contain one by oneIf you add them to the list, you don't see them as a whole.

Examples are as follows:
Example 1, add data as a string

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
list_demo1.extend('Magnon Ajie')  # The data added to the end of list_demo1 using the extend() function is a string
print('---- List after adding elements ----: ')
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number',':','Yard','Nong','A','Jet']

Example 2, Add data as a list

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.extend([1, 2, 3])  # Use the extend() function to add data to the end of list_demo1 as a list
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number',':', 1, 2, 3]

Example 3, adding data as tuples

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.extend((1, 2, 3))  # The data added to the end of list_demo1 with the extend() function is a tuple
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number',':', 1, 2, 3]

5.1.3 Python insert() method insert element

The format is as follows:

listname.insert(index , obj)

For the above formats,

  • The insert():insert() method inserts an element at a specified location in the middle of the list.The append(), extend() methods can only insert elements at the end of the list.
  • listname: represents the list of elements to be inserted.
  • Index: Indicates the index value for the specified location.
  • obj: The data to be inserted into the list.If the inserted data is a list or tuple, insert() also treats them as a whole and inserts them into the list as an element, in the same way as append() does.

Examples are as follows:
Example 1, insert data as a string

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.insert(1, 'Magnon Ajie')  # Data added to list_demo1 with an index value of 1 using insert() method is a string
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number','Menon Ajie',':']

Example 2, Insert data as a list

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.insert(1, [1, 2, 3])  # The data added to the list_demo1 with an index value of 1 by insert() is a list
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number', [1, 2, 3],':']

Example 3, insert data as tuples

list_demo1 = ['WeChat Public Number', ': ']  # list_demo1 to add elements
print('---- Original List ----: ')
print(list_demo1)
print('---- List after adding elements ----: ')
list_demo1.insert(1, (1, 2, 3))  # Data added to list_demo1 with an index value of 1 by insert() method is tuple
print(list_demo1)

Run result:

--- Original List----:
['WeChat Public Number',':']
------:
['WeChat Public Number', (1, 2, 3),':']

5.1.4 Other methods (using the + addition operator)

Use the + addition operator to add two or more lists together for the purpose of splicing lists, which will result in a new list without changing the original list.

In terms of execution efficiency, this method is not recommended because it is less efficient.

It is recommended to use the methods described earlier (specialization in the art, specialization in the art).

Examples are as follows:

list1 = ['WeChat Public Number:']
list2 = ['Magnon Ajie']

print('list1 =', list1)
print('list2 =', list2)
print('list1 + list2 =', list1 + list2)

Run result:

list1 = ['WeChat Public Number:']
list2 = ['Magnon Ajie']
list1 + list2 = ['WeChat Public Number:', 'Magnon Ajie']

5.2 Delete (delete list elements)

5.2.1 Delete based on the index of the location of the target element

Deleting based on the index of the location of the target element requires either the del keyword or the pop() method.

The del keyword, which is designed to perform deletion operations, not only deletes the list, but also deletes some elements in the list.
pop() method, deletes the element in the list at the specified index.

The format used is as follows:

del listname[index]  # Delete a single element from the list
del listname[start : end]  # Delete a contiguous segment of the list. del deletes elements from index start to end, excluding those at the end. 

For the above formats,

  • listname represents the list of elements to be deleted.
  • Index indicates the index value of the element to be deleted.
  • start represents the starting index value.
  • The end indicates the end index value.
listname.pop(index)

For the above formats,

  • listname represents the list of elements to be deleted.
  • Index indicates the index value of the element to be deleted.If you do not write the index parameter, the last element in the list is deleted by default.

Examples are as follows:

For example, use the del keyword to delete a list element
(1) Delete a single element using the del keyword

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie']  # List of elements to delete

print('Delete the list before, list_demo =', list_demo)
del list_demo[1]  # Delete the element corresponding to index value 1
print('Deleted list, list_demo =', list_demo)

Run result:

Delete the list before, list_demo = ['WeChat Public Number',':','Manon Ajie']
Deleted list, list_demo = ['WeChat Public Number','Menon Ajie']

(2) Delete a consecutive element using the del keyword

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie']  # List of elements to delete

print('Delete the list before, list_demo =', list_demo)
del list_demo[0: 2]  # Delete index values 0 to 2, excluding consecutive elements corresponding to 2
print('Deleted list, list_demo =', list_demo)

Run result:

Delete the list before, list_demo = ['WeChat Public Number',':','Manon Ajie']
Deleted list, list_demo = ['Menon Ajie']

Example 2, using the pop() method to delete a list element
(1) Specify the index parameter

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie']
print('Before deletion: list_demo =', list_demo)
list_demo.pop(1)  # Delete element with index value of 1
print('After deletion: list_demo =', list_demo)

Run result:

Before deletion: list_demo = ['WeChat Public Number',':','Menon Ajie']
Deleted: list_demo = ['WeChat Public Number','Menon Ajie']

(2) The index parameter is not specified

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie']
print('Before deletion: list_demo =', list_demo)
list_demo.pop()  # Remove the last element by default without specifying the index parameter
print('After deletion: list_demo =', list_demo)

Run result:

Before deletion: list_demo = ['WeChat Public Number',':','Menon Ajie']
Deleted: list_demo = ['WeChat Public Number',':']

5.2.2 Delete based on the value of the element itself

To delete an element based on its own value, use the remove() method provided by the list.

The format used is as follows:

listname.remove(element)

For the above grammar format instructions:

  • The remove():remove() method deletes elements based on their own values.Note that: (1) the method only deletes the first specified element that is encountered; if there are identical elements in the list, they will not be deleted; and (2) the element to be deleted must be guaranteed to exist in the list, otherwise an error will be made.
  • listname: The list of elements to be deleted.
  • Element: The element to be deleted.

Examples are as follows:
(1) There are elements in the list that are specified to be deleted

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie', 'WeChat Public Number']
print('Before deletion: list_demo =', list_demo)
list_demo.remove('WeChat Public Number')  # Delete the specified element WeChat Public Number, only the first specified element you meet will be deleted
print('After deletion: list_demo =', list_demo)

Run result:

Before deletion: list_demo = ['WeChat Public Number',':','Manon Ajie','WeChat Public Number']
Deleted: list_demo = [':','Menon Ajie','WeChat Public Number']

(2) There is no element specified to delete in the list

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie', 'WeChat Public Number']
print('Before deletion: list_demo =', list_demo)
list_demo.remove('Wechat number')  # There is no element specified to delete in the list, error will occur
print('After deletion: list_demo =', list_demo)

Run result:

Before deletion: list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie', 'WeChat Public Number']
Traceback (most recent call last):
  File "D:/Data/ProfessionalSkills/Python/PycharmProjects/demo/demo.py", line 16, in <module>
    list_demo.remove('Wechat number')  # There is no element specified to delete in the list, error will occur
ValueError: list.remove(x): x not in list

5.2.3 Delete all elements in the list

To delete all elements in a list, you need to use the clear() method provided by the list.

The format used is as follows:

listname.clear()

For the above formats,

  • The clear():clear() method deletes all elements in the list.
  • listname: The list of elements to be deleted.

Examples are as follows:

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie']
print('Before deletion: list_demo =', list_demo)
list_demo.clear()  # Delete all elements in the list, also known as empty list
print('After deletion: list_demo =', list_demo)

Run result:

Before deletion: list_demo = ['WeChat Public Number',':','Menon Ajie']
After deletion: list_demo = []

5.3 Change (modify list elements)

5.3.1 Modify a single element

The format is as follows:

listname[index] = element

For the above formats,

  • listname: The list of elements to be modified.
  • Index: The index value corresponding to the element is to be modified.
  • Element: The new element value.

Examples are as follows:

list_demo = ['Wechat number', ': ', 'Magnon Ajie']
print('Before modification: list_demo =', list_demo)
list_demo[0] = 'WeChat Public Number'  # Modify an element with an index value of 0
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = ['Microsignal',':','Manon Ajie']
Modified: list_demo = ['WeChat Public Number',':','Menon Ajie']

5.3.2 Modifying a set of elements

Modifying a set of elements means assigning values to a set of elements using slicing.However, a single assignment (usually an exponential word) is not supported.If it is a string, Python automatically converts the string into a sequence, where each character is an element.

If no step size is specified (that is, no step parameter is specified), the number of elements newly assigned can be different from the number of elements originally assigned.This means that it can either add elements to the list (assign values to empty slices) or delete elements from the list.

If a step is specified, the number of elements to be newly assigned is the same as the number of elements to be assigned.

Examples are as follows:
Example 1, no step specified
(1) Modify the value of a set of elements

list_demo = ['Wechat number', '=', 'Magnon Ajie', '. ']
print('Before modification: list_demo =', list_demo)
list_demo[0: 2] = ['WeChat Public Number', ': ']
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = ['Micro Signal','=','Manon Ajie','.']
After modification: list_demo = ['WeChat Public Number',':','Manon Ajie','.']

(2) Individual assignments are not supported (usually exponential words)

list_demo = ['Wechat number', ': ', 'Magnon Ajie', '. ']
print('Before modification: list_demo =', list_demo)
list_demo[0: 0] = 12  # Single assignment (number) is not supported
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = ['Wechat number', ': ', 'Magnon Ajie', '. ']
Traceback (most recent call last):
  File "D:/Data/ProfessionalSkills/Python/PycharmProjects/demo/demo.py", line 36, in <module>
    list_demo[0: 0] = 12
TypeError: can only assign an iterable

(3) Individual assignments (usually exponential words) are not supported, but if it is a string, Python automatically converts the string into a sequence, where each character is an element

list_demo = ['Wechat number', ': ', 'Magnon Ajie', '. ']
print('Before modification: list_demo =', list_demo)
list_demo[0: 0] = 'WeChat Public Number'  # Individual assignments (usually exponential words) are not supported, but if it is a string, Python automatically converts the string into a sequence, where each character is an element
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = ['Micro Signal',':','Manon Ajie','.']
After modification: list_demo = ['Micro','Xin','Gong','Crowds','Number','Micro Signal',':','Manon Ajie','.']

(4) Add elements to the list (assign values to empty slices)

list_demo = ['Magnon Ajie']
print('Before modification: list_demo =', list_demo)
list_demo[0: 0] = ['WeChat Public Number', ': ']  # Assigning values to empty slices
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = ['Menon Ajie']
Modified: list_demo = ['WeChat Public Number',':','Menon Ajie']

(5) Delete elements for lists

list_demo = ['WeChat Public Number', ': ', 'Magnon Ajie', '. ']
print('Before modification: list_demo =', list_demo)
# There are many ways to write a slice here, such as list_demo[:], list_demo[0:], list_demo[0:4], list_demo[-4:], etc. Not all of them are listed, so you can study the slice.
list_demo[:] = ['WeChat Public Number', ': ', 'Magnon Ajie']  # The number of elements newly assigned can be different from the number of elements originally assigned.Equivalent to reassigning a list with fewer elements.
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = ['WeChat Public Number',':','Manon Ajie','.']
Modified: list_demo = ['WeChat Public Number',':','Menon Ajie']

Example 2, specifying a step

list_demo = [1, 2, 3, 4, 5, 6, 7]  # For clarity, add letters to the list of pure numbers
print('Before modification: list_demo =', list_demo)
list_demo[1: 6: 2] = ['a', 'b', 'c']  # Add a new element every two, starting at index 1, to index 6, excluding index 6
print('After modification: list_demo =', list_demo)

Run result:

Before modification: list_demo = [1, 2, 3, 4, 5, 6, 7]
Modified: list_demo = [1,'a', 3,'b', 5,'c', 7]

5.4 Search (Find List Elements)

5.4.1 Find elements using the index() method provided by the list

The format used is as follows:

listname.index(obj, start, end)

For the above formats,

  • Return value: The index() method returns the position (index) where an element appears in the list.If the element found does not exist, an error will be reported.
  • listname: Represents the name of the list.
  • obj: Indicates the element to be found.
  • start: Indicates the starting position.Can not write, meaning to retrieve elements from the beginning to the end (excluding the end).
  • End: denotes the end position.Can not write, meaning retrieving elements from start to end.
  • Start and end can be neither written, meaning to retrieve the entire list; both written, meaning to retrieve elements between start and end (excluding end).

Examples are as follows:

list_demo = [1, 2, 3, 4, 5, 6, 7]  # list

index1 = list_demo.index(3)  # Retrieve the location of element 3 throughout the list
print('Retrieve the location of element 3 throughout the list:', index1)

index2 = list_demo.index(3, )
print('Retrieve the location of element 3 throughout the list:', index2)

index3 = list_demo.index(3)  # Retrieves the position of element 3 in the list (the index value in the list)
print('Element 3 is in the list:', index3)

index4 = list_demo.index(3, 0, 3)  # Retrieve the position of element 3 in the list between index values 0 and 3
print('Retrieving element 3 from index value 0 to 3 has the following position in the list:', index4)

index5 = list_demo.index(3, 0, 2)  # Retrieving the position of element 3 in the list between index values 0 and 2 will cause an error because there is no element 3 in this range
print('Retrieve the position of element 3 in the list between index values 0 and 2:', index5)

# index6 = list_demo.index(11)  # Error will also occur because there is no element to look for in the list
# print(index6)

Run result:

Retrieve the location of element 3 in the entire list: 2
//Retrieve the location of element 3 in the entire list: 2
//The position of element 3 in the list is: 2
//Retrieving element 3 from index value 0 to 3 has the following position in the list:
Traceback (most recent call last):
  File "D:/Data/ProfessionalSkills/Python/PycharmProjects/demo/demo.py", line 69, in <module>
    index5 = list_demo.index(3, 0, 2)  # Retrieving the position of element 3 in the list between index values 0 and 2 will cause an error because there is no element 3 in this range
ValueError: 3 is not in list
#Traceback (most recent call last):
#  File "D:/Data/ProfessionalSkills/Python/PycharmProjects/demo/demo.py", line 72, in <module>
#    index6 = list_demo.index(11)  # Error will also occur because there is no element to look for in the list
#ValueError: 11 is not in list

5.4.2 Find elements using the count() method provided by the list

The format used is as follows:

listname.count(obj)

For the above formats,

  • Return value of count(): The count() method returns the number of times an element appears in the list.If 0 is returned, the element does not exist in the list.
  • listname: Represents the list name.
  • obj: Represents the element to be counted.

Examples are as follows:

list_demo = [1, 2, 3, 4, 3, 6, 3]  # list

nums1 = list_demo.count(3)  # Number of occurrences of statistic element 3 in the list
print('Number of times element 3 appears in the list:', nums1, 'Second.')

# Determine if element 7 exists in the list
nums2 = list_demo.count(7)

if nums2:
    print('Element 7 exists in the list ')
else:
    print('Element 7 does not exist in the list ')

Run result:

Number of times the statistic element 3 appears in the list: 3 times.
Element 7 does not exist in the list 

6 List Sorting

6.1 Sort using the sort() method provided by the list

For in-place sorting of lists, you can use the sort() method provided by the list itself.

The format used is as follows:

listname.sort(*, key=None, reverse=False)

For the above formats,

  • The sort():sort() method sorts the list in place, modifying it.
  • The sort() method accepts two parameters that are only passed in as keywords.
  • Key: Specifies a function with one parameter to extract a comparison key from each list element (for example, key=str.lower).The keys corresponding to each item in the list are calculated once and used throughout the sorting process.The default value None means that the list items are sorted directly without calculating a single key value.
  • Reverse:reverse is a Boolean value.The default is False, meaning ascending sort.If set to True, each list element is sorted by a reverse (descending) comparison.

Examples are as follows:
Example 1,

list_demo = [4, 1, 3, 2, 8, 5]

print('Before Sorting list_demo =', list_demo)
list_demo.sort()  # Sort list in ascending order
# list_demo.sort(reverse=False)  # The ascending sort operation can also be written like this
print('After Ascending Sort list_demo =', list_demo)
list_demo.sort(reverse=True)  # Sort in descending order
print('After descending sort list_demo =', list_demo)

Run result:

Pre-sorted list_demo = [4, 1, 3, 2, 8, 5]
list_demo = [1, 2, 3, 4, 5, 8] after ascending sort
 list_demo = [8, 5, 4, 3, 2, 1] after descending sort

Example 2,

# Prepare dispatch functions for key parameters
def take_second(element):
    return element[1]


list_demo = [(1, 3), (3, 5), (2, 4), (5, 1)]

print('Before Sorting list_demo =', list_demo)
list_demo.sort()  # Sort ascending.The tuple is the element of the list, and the sort is compared with the first element of the tuple.
print('Tuples are the elements of the list, and sorting is compared with the first element of the tuple list_demo =', list_demo)
list_demo.sort(key=take_second)  # Sort ascending.The tuple is the element of the list, and the sort is compared with the second element of the tuple.
print('Tuples are the elements of the list, and sorting is compared with the first element of the tuple list_demo =', list_demo)

Run result:

Pre-sorted list_demo = [(1, 3), (3, 5), (2, 4), (5, 1)]
The tuple is the element of the list, sorted by comparing list_demo = [(1, 3), (2, 4), (3, 5), (5, 1)] with the first element of the tuple
 A tuple is an element of the list, sorted by comparing list_demo = [(5, 1), (1, 3), (2, 4), (3, 5)] with the first element of the tuple

6.2 Sorting using the sorted() built-in function

Build a new sort list from an iterative object using the sorted() built-in function.

The format used is as follows:

sorted(iterable, * ,key=None, reverse=False)

For the above formats,

  • Return value: The sorted() built-in function returns a new sorted list based on items in the iterable.
  • There are two optional parameters that must be specified as keyword parameters.
  • Key: Specifies a function with a single parameter to extract the key for comparison from each element of the iterable (for example, key=str.lower).The default value is None (Direct Compare Elements).
  • Reverse: is a Boolean value.The default is False, meaning ascending sort.If set to True, each list element is sorted by a reverse (descending) comparison.

Examples are as follows:

# Prepare dispatch functions for key parameters
def take_second(element):
    return element[1]


list_demo = [(1, 3), (3, 5), (2, 4), (5, 1)]

print('Before Sorting list_demo =', list_demo)
new_list1 = sorted(list_demo, key=None)  # Sort ascending.The tuple is the element of the list, and the sort is compared with the first element of the tuple.
print('Tuples are the elements of the list, and sorting is compared with the first element of the tuple list_demo =', new_list1)
new_list2 = sorted(list_demo, key=take_second)  # Sort ascending.The tuple is the element of the list, and the sort is compared with the second element of the tuple.
print('Tuples are the elements of the list, and sorting is compared with the first element of the tuple list_demo =', new_list2)

Run result:

Pre-sorted list_demo = [(1, 3), (3, 5), (2, 4), (5, 1)]
The tuple is the element of the list, sorted by comparing list_demo = [(1, 3), (2, 4), (3, 5), (5, 1)] with the first element of the tuple
 A tuple is an element of the list, sorted by comparing list_demo = [(5, 1), (1, 3), (2, 4), (3, 5)] with the first element of the tuple

7 Articles Other Addresses

7.1 WeChat Public Number: Nun Ajie

7.2 CSDN Blog

8 References

8.1 Python 3.8.2 documentation

Tags: Python Java PHP less

Posted on Tue, 05 May 2020 11:35:00 -0400 by timmy0320