Pthon Learning Records - List

list

What is a list

  • A list is an ordered, variable sequence
  • Variables can store one element, while lists are "big containers" that can store more than N elements, making it easy for programs to manipulate the data as a whole
  • Lists are equivalent to arrays in other languages
  • The list actually stores a reference to an object (id)

List Creation

Lists need brackets [], elements separated by commas in English

- Use brackets[]
- Calling built-in functions list()

Features of lists

- List elements are ordered in order
- Index Mapping Unique Data
- Lists can store duplicate data
- Any data type mix
- Dynamically allocate and reclaim memory as needed

Query operation of list (slicing operation)

  • Gets the index of the specified element - given element, finds the index value - index()
    • If there are identical elements in the list, only the index of the same element in the list is returned as one element
    • If the element of the query is not in the list, a ValueError exception is thrown
    • Can be found between a specified start and stop (start from start to stop, but do not include stop)
lst = ['hello','world',98,'hello']
print(lst.index('hello'))   # 0 If there are identical elements in the list, only the index of the first element of the same element in the list is returned
# print(lst.index(222))       #ValueError: 222 is not in list
print(lst.index('world',0,3))   #0
  • Get a single element in the list - Given a specified index value, find the corresponding element
    • Forward index from 0 to N-1
    • Reverse index from -N to -1
    • Throw an IndexError exception when the specified index does not exist
  • Getting multiple elements in a list -- slicing
    • Grammatical Structure

      List Name[ start	:	stop	:step	]
      
    • The structure of the slice - ->a copy of the original list fragment

    • The extent of the slice - - >[start, stop]

    • Step size step defaults to 1 --> abbreviated as [start: stop] or [start: stop:]

    • When step is positive: cut back from start

      • [: stop: step] -->The first element of the slice is the first element of the list by default
      • [start:: step] ->The last element of the slice is the last element of the list by default
    • When step is negative: cut forward from start

      • [: stop: step] -->The first element of a slice defaults to the last element of the list
      • [start:: step] - > The last element of the slice is the first element of the list by default
lst = [10, 20, 30, 40, 50, 60, 70, 80]
# start=1,stop=6,step=1
print('Original List lst', lst, id(lst))  # Original list lst [10, 20, 30, 40, 50, 60, 70, 80] 2052109247744

print('New List lst2', lst[1:6:1], id(lst[1:6:1]))  # New list lst2 [20, 30, 40, 50, 60] 2052109587456

print(lst[1:6])  # [20, 30, 40, 50, 60]
print(lst[1:6:])  # [20, 30, 40, 50, 60]

# start=1,stop=6,step=2
print('New List lst3', lst[1:6:2])  #[20, 40, 60]

# When step is positive: start defaults, stop=6,step=2 - start defaults to 0
print('New List lst4', lst[:6:2])  #[10, 30, 50]

# When step is positive: start=1,stop defaults, step=2 - stop defaults to last
print('New List lst5', lst[1::2])  #[10, 30, 50]

# When step is negative
print('New List lst6', lst[::-1])  #[80, 70, 60, 50, 40, 30, 20, 10]

# When step is a negative number: start=7,stop omitted, step=-1
print('New List lst7', lst[7::-1])  #[80, 70, 60, 50, 40, 30, 20, 10]

# When step is a negative number: start=6,stop=0,step=-1
print('New List lst8', lst[6:0:-2])  #[70, 50, 30]
* Determines whether the specified element exists in the list
	- element in List Name
	- element not in List Name
* Traversal of list elements
	- for Iterative traversal  in  List name:
	- 			operation

Adding List Elements

  • append()->Add an element to the end of the list, and do not produce new objects
  • extend()->Add at least one element to the end of the list
  • insert()-->Add an element anywhere in the list
  • Slice --->Add at least one element anywhere in the list
# Add an element to the end of the list
lst = [10, 20, 30]
print('Before adding elements', lst)
lst.append(100)
print('After adding elements', lst)

lst2 = ['hello', 'world']
lst.append(lst2)  # Add list2 as an element to the end of the list
print(lst)  # [10, 20, 30, 100, ['hello', 'world']]
lst.extend(lst2)  # Add more than one element at a time like the end of the list
print(lst)  # [10, 20, 30, 100, ['hello', 'world'], 'hello', 'world']

# Add elements anywhere
lst.insert(1, 90)
print(lst)  # [10, 90, 20, 30, 100, ['hello', 'world'], 'hello', 'world']

# Add N elements anywhere
lst3 = [True, False, 'hello']
lst[1::] = lst3
print(lst)  # [10, True, False, 'hello']

Deleting List Elements

  • remove()->Remove an element from the list, if there are duplicate elements, remove only the first one
  • pop()->Remove elements by index; throw an IndexError exception if the index does not exist
  • Slice - > Deleting at least one element will result in a new list object
  • clear()->Empty list
  • del->Delete List
lst = [10, 20, 30, 40, 50, 60, 30]
lst.remove(30)  # Remove an element from the list, only the first element if there are duplicate elements
print(lst)  # [10, 20, 40, 50, 60, 30]
# lst.remove(100) #ValueError: list.remove(x): x not in list

# pop() removes elements by index
lst.pop(1)
print(lst)  # [10, 40, 50, 60, 30]
# lst.pop(5) #IndexError: pop index out of range throws an exception if the specified index location does not exist
lst.pop()  # If no parameter (index) is specified, the last element in the list will be deleted
print(lst)  # [10, 40, 50, 60]

print('----------Slicing operation-Deleting at least one element will result in a new list object-------------------')
new_list = lst[1:3]
print('Original List', lst)  # Original List [10, 40, 50, 60]
print('List after slicing', new_list)  # Sliced list [40, 50]

'''Do not generate new list objects, but delete the contents of the original list'''
lst[1:3] = []
print(lst)  # [10, 60]

'''Clear all elements in the list'''
lst.clear()
print(lst)  # []

'''del Statement deletes list objects'''
del lst
# print(lst) #NameError: name 'lst' is not defined

Modification of List Elements

  • Assigns a new value to the element of the specified index
  • Assign a new value to the specified slice
list=[10,20,30,40]
# Modify one value at a time
list[2]=100
print(list) #[10, 20, 100, 40]
# Slice modification
list[1:3:]=[22,33]
print(list)

Sort operation of list elements

  • Sort()->Calls the sort() method. All elements in the list are sorted from smallest to largest by default, and can be sorted in descending order by specifying reverse=True. Operation on the original list will not result in new list objects
  • Sorted()->Call the built-in function sorted(), which can be sorted in descending order by specifying reserve=True, without changing the original list, resulting in a new list object
lst = [20, 40, 10, 98, 54]
print('Pre-Sort List', lst)  # Pre-Sort List [20, 40, 10, 98, 54]
# Start sorting, call the sort method of the list object, default is ascending
lst.sort()
print('Sorted List', lst)  # Sorted list [10, 20, 40, 54, 98]
lst.sort(reverse=True)
print('New Sort List', lst)  # New Sort List [98, 54, 40, 20, 10]
lst.sort(reverse=False)
print('New Sort List', lst)  # New Sort List [10, 20, 40, 54, 98]

# Sorting a list using the built-in function sorted() will result in a new list object
lst2 = sorted(lst)
print(lst2)  # [10, 20, 40, 54, 98]
lst2 = sorted(lst, reverse=True)
print(lst2)  # [98, 54, 40, 20, 10]

List Generation

-  Grammar Format
	- [ i*i for i in range(1,10) ]

Where i*i is an expression for a list element and typically contains a custom variable

lst = [i for i in range(1, 10)]  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(lst)
lst2 = [i * i for i in range(1, 10)]  # [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(lst2)

# The values of the elements in the list are 2, 4, 6, 8, 10
lst3 = [i * 2 for i in range(1, 6)]  # [2, 4, 6, 8, 10]
print(lst3)

Keywords: Python

Added by steveness on Sat, 16 Oct 2021 19:49:25 +0300