“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”

List and Tuple operations

Sort function

Sort (‘ reverse=Tue ‘or’ False ‘); sort (‘ reverse=Tue ‘or’ False ‘); sort (‘ True ‘or’ descending ‘)

To sort a list, the elements in the list must be of the same type, otherwise it cannot be sorted

list_str = ['2051'.'2022'.1[1.2.3]]

print('List order before sort: {}'.format(list_str))
list_str.sort()

print('Sorted list order: {}'.format(list_str))
Copy the code

list_str = ['2051'.'2022'.'2040'.'2050']

print('List order before sort: {}'.format(list_str))
list_str.sort()

print('Sorted list order: {}'.format(list_str))
Copy the code

list_str = ['2051'.'2022'.'2040'.'2050']

print('List order before sort: {}'.format(list_str))
list_str.sort(reverse=True)

print('Sorted list order: {}'.format(list_str))
Copy the code

Sort passes arguments reverse=True in descending order

The clear function

The clear function clears the current list, passing no arguments and returning no value

list_str = ['2051'.'2022'.'2040'.'2050']

print('Clear column: {}'.format(list_str))
list_str.clear()

print('Clear list: {}'.format(list_str))
Copy the code

The copy function

The copy function assigns the current list to an identical list with the same contents as the old list, but with a different memory address. Copy takes no arguments; Return an identical list

The difference between copy and secondary assignment:

  • The secondary assignment has the same memory address as the original variable
  • The memory address of the list returned by copy is different from the original list
  • The list returned by copy and the original list are two lists. Modifying the contents of one list has no effect on the contents of the other list. Since both variables point to the same block of memory, all changes have an effect on both variables
  • Copy Indicates a shallow copy

Shallow copy, there is a list A, the elements of the list and the list, when a copy of the new list B, whether a or B internal list data changes, will be affected by each other

list_01 = [
            ['stark'.'peter'],
            ['banner'.'steve'],
            [1.5.8.9]
           ]

list_01_copy = list_01.copy()

print(list_01_copy)

# Change the elements in the list
list_01[0].append('clint')

print(list_01_copy)
Copy the code

Changes to only the first layer of data are not affected; nested lists are

The deep copy not only copies the first layer data, but also copies the deep layer data. The original variable and the new variable are completely two variables, and the modification does not affect each other

import copy

list_01 = [
            ['stark'.'peter'],
            ['banner'.'steve'],
            [1.5.8.9]]# deep copy
list_01_deepcopy = copy.deepcopy(list_01)

print(list_01_deepcopy)

# Change the elements in the list
list_01[0].append('clint')

print(list_01_deepcopy)

print('list_01 memory address: {}'.format(id(list_01)))
print('list_01_deep_copy memory address: {}'.format(id(list_01_deepcopy)))
Copy the code

You need to import the copy module for deepcopy and call deepcopy to complete the operation. The list returned by the call is a new list with a different memory address

The extend function

The extend function imports elements from other lists or tuples into the current list, taking as arguments an iterable datatype such as a list tuple dictionary string. This function returns no value

heros = ['stark']
hero = ['thor'.'loki'.'banner' ]

heros.extend(hero)
print(heros)

heros.extend(('peter'.'strange'))
print(heros)

heros.extend('hello')
print(heros)

heros.extend({'name': 'pipi'})
print(heros)
Copy the code

When the dictionary is passed in, only Value is added to the list.

heros = ['stark']
heros.extend(None)
Copy the code

Pass in an int

heros = ['stark']
heros.extend(12)
print(heros)
Copy the code

Passing in bool

heros = ['stark']
heros.extend(True)
print(heros)
Copy the code

Index and slice the list

The leftmost position recorded in strings, tuples, and lists is the index, which is represented by a number starting at 0

The index starts at 0, so the maximum index is of length -1

Index is used to access a single element, while slice is used to access elements with certain rhetorical questions. Slice uses a colon to find out the two separated indexes in brackets, and the rule of slice is left and right inclusive

nums = [1.2.3.4.5.6.7]

print('The maximum index of a NUMs list is: {}'.format(len(nums) - 1))
print('The element at index 4 is: {}'.format(nums[4]))

print('Get the full nums list:',nums[:])
print('Second way to get the full list:',nums[0:)print('Get list except last element:', nums[:-1])
Copy the code

The default slice starting index is 0 and contains elements indexed at 0

nums = [1.2.3.4.5.6.7]

new_entire_nums = nums[:]
print('Original list id:'.id(nums))
print('New list ID:'.id(new_entire_nums))
Copy the code

Slicing gets a different list ID than the original list, and slicing generates a new list

nums = [1.2.3.4.5.6.7]

print(nums[-3: -1])
print(nums[-7: -1])
print(nums[-7:6])
Copy the code

The indexes in the list are -1 from right to left, -2 and -3…..

In addition to passing in two indexes for slicing, you can also pass in a third value, namely the step length, which is 1 by default, and is obtained from left to right. If the index is negative, it is obtained from right to left by the step length

nums = [1.2.3.4.5.6.7]

print(nums[-3: -1])
print(nums[-7: -1:3])
print(nums[-7:6:2])
print(nums[6: -7: -2])
Copy the code

Get the list index

List [index]=new_item can be used to modify elements in a list. Data can only be modified within the scope of existing indexes

The index function retrieves the index of an element in a list

heros = ['stark'.'peter'.'banner'.'thor'.'loki']

idx_01 = heros.index('banner')
print('Banner's index in the list is:', idx_01)

idx_02 = heros.index('wanda')
print('Wanda's index in the list is:', idx_02)
Copy the code

An error occurs when the element being searched does not exist in the list

# index modifies elements
heros = ['stark'.'peter'.'banner'.'thor'.'loki']
heros[2] = 'wanda'
print(heros)
heros[-1] = 'clint'
print(heros)
# Change the slice mode
heros[1:3] = 'hulk'.'wonder woman'
print(heros)
heros[1:3:2] = ['Captain']
print(heros)
Copy the code