List operations in Python

Posted by eddie21leeds on Thu, 05 Dec 2019 15:53:26 +0100

Basic details of the list

  1. Include content in brackets
  2. Modifiable data type
  3. Support nesting
  4. Support index, slice, multiply and add operation, member check, length, minimum value and maximum value

 

List assignment to variable

list1 = ['hello', 'world']

 

Append to list

list1 = ['hello', 'world']
list1.append('!')           # Can only be appended to the end of the list

 

Insert content in list

list1 = ['hello', 'world']
list1.insert(1,',')         # Specify index location insert content

 

Nesting of list and list

list1 = [1, 2, 3, [11, 22, 33]]

 

Delete the specified element in the list

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
list1.remove('a')

 

Delete index content in list

Method 1

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
list1.pop(2)        # Return value

 

Method 2

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
del list1[1]        # No return value

 

Delete entire list

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
del list1

 

Clear entire list

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
list1.clear()

 

Print list length

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
print(len(list1))

 

Print list index location content

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
print(list1[0])

 

Print list slice location content

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
print(list1[0:3])

 

Print list specify content index

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
print(list1.index('a'))         # If the content is not in the list, an error will be reported

 

Print list specified content times

list1 = ['a', 'b', 'c', 1, 2, 3, [11, 22, 33]]
print(list1.count('a'))

 

Sort list

list1 = [1, 3, 44, 4, 33, 11, 2, 5]
list1.sort()                    # Forward sort
list1.sort(reverse=True)        # Reverse sorting
list1.reverse()                 # Reverse the entire list

 

Index content change in list

li = ['Taibai','Li Bai','Centenary mountain']
print(li[2].replace('hundred', 'white'))  # replace The contents of the list will not be changed directly, and the replacement of numbers is not supported

 

Index change in list

list1 = ['Taibai','Li Bai','Centenary mountain']
list1[0] = 'Too black'

 

Slice changes in list

list1 = ['Taibai','Li Bai','Centenary mountain']
list1[0:3] = 'Too black','Taibai','Reversi'

 

Minimum element added to list

list1 = []
list1.extend('Zhang Wuji') # Will bring'Zhang Wuji'Three words are separated and added to the list as three elements. The length of the list is 3. This method supports iterative addition

 

List conversion string

list1 = ['zhangsan', 'lisi', 'wangwu']
str1 = ','.join(list1)

 

Note: all the addition, deletion and modification operations in the list directly change the original memory address, and do not need to be reassigned

Topics: Python