Learn python from scratch day 3

Pre questions:

Q1: what do lists and tuples belong to?
Q2: what are the similarities and differences between lists and tuples?

Learning content:

1. Definition of sequence.
1. List features, creation and common operations.
2. Characteristics, creation and common operations of tuples.

Learning output:

1. Sequence

1.1 definitions

A method of data storage in which multiple values are stored in a continuous memory space.

1.2 what are the sequences

Strings, lists, tuples, dictionaries, and collections all belong to sequences

1.3 memory storage mode diagram

A1

Lists and tuples belong to sequences

2. List list

2.1 definitions

Use a continuous storage space to store any number and any type of data sets.

2.2 creation method

  • Basic syntax [] create
>>> a = [1,2,3,56,"hahaha","python"]
>>> a
[1, 2, 3, 56, 'hahaha', 'python']
  • list() create
>>> b = list() #Create an empty list of objects
>>> b = list(range(10))
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> b = list("i love you")
>>> b
['i', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u']

  • range() create
    Format: range(start, end, step) start parameter is optional, and the default is 0; The end parameter is required, indicating the ending number; The step parameter is optional. The default value is 1
>>> list(range(1,10,2))
[1, 3, 5, 7, 9]

>>> list(range(20,10,-1))
[20, 19, 18, 17, 16, 15, 14, 13, 12, 11]
  • Derivation creation
>>> a = [x * 2 for x in range(5)]  
>>> a
[0, 2, 4, 6, 8]

>>> b = [x * 2 for x in range(100) if x%3 == 0]
>>> b
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198]

Explanation: first execute the loop x = (0, 1, 2, 3, 4), then execute x*2 = (0, 2, 4, 6, 8), and finally generate the list

2.3 common methods

  • Add: append(), +, extend()
methodexplaindifference
append()Add an element at the end of the listThere is no need to create a new object and modify the original value. It is highly efficient and recommended
+String like splicingYou need to create a new object, which wastes memory and takes a long time
extend()Expand the list, and expand the elements to the back of the listThere is no need to create an object and modify it on the original value
>>> list1 = [20,30,40]
>>> list1.append(50)
>>> list1
[20, 30, 40, 50]
>>> id(list1)
1971841232512

>>> list1 = list1 + [60]
>>> list1
[20, 30, 40, 50, 50, 60]
>>> id(list1)					#Address changed
1971840978432

>>> list1.extend([70,80])
>>> list1
[20, 30, 40, 50, 50, 60, 70, 80]

  • Insert: insert()
    1. The essence of the insert method is that the element moves back, which wastes a lot of time.
    2. insert method graph representation
>>> list1 = [10,20,30,50,60]
>>> list1.insert(3,40)
>>> list1
[10, 20, 30, 40, 50, 60]

  • Delete: del list_name[] ,pop(),remove()
    1,del list_ The essence of the name [] method is to move the element forward
    2. del method graph representation

3. pop(): pop up the element in the list and return it. The default is to select the last element in the list. You can also specify the element subscript.

4. remove(): deletes the element that appears for the first time in the list. If the element is not in the list, an error is reported.

>>> list2 = [10,20,30,40,50,70,60]
>>> list2
[10, 20, 30, 40, 50, 70, 60]
>>> del list2[5]
>>> list2
[10, 20, 30, 40, 50, 60]

>>> list3 = [10 ,70, 20, 30, 40, 50, 60]
>>> list3
[10, 70, 20, 30, 40, 50, 60]
>>> list3.pop(1)
70
>>> list3
[10, 20, 30, 40, 50, 60]

>>> list4 = [10,20,30,40,40,40,50,60,70]
>>> list4
[10, 20, 30, 40, 40, 40, 50, 60, 70]
>>> list4.remove(40)
>>> list4
[10, 20, 30, 40, 40, 50, 60, 70]

  • Index, count and list length: index(), count(), len()

1. index(): Specifies the position where the element appears in the list for the first time; Format list Index (x [, start [, end]]) the start and end parameters are not necessary. Start means to search backward from the first position. The element is not in the list, and start~end is in this range.

2. count(): Specifies the number of times the element appears in the list. If not, it returns 0 times

3. len() returns the length of the list.

>>> list4 = [10,10,20,20,30,30,40,50,19]
>>> list4
[10, 10, 20, 20, 30, 30, 40, 50, 19]
>>> list4.index(10,2)
Traceback (most recent call last):
  File "<pyshell#128>", line 1, in <module>
    list4.index(10,2)
ValueError: 10 is not in li

>>> list4.index(30,2,5)
4
>>> list4[4]
30

>>> list4.count(20)
2
>>> list4.count(90)
0

>>> len(list4)
9

  • characteristic:
    Variable element size

  • List slice
    Slicing method of the same string

  • sort list
    1. sort(): sort in place
    2. sorted(): create a new sort list
    3. reversed() returns the iterator, reverses the list, does not modify the original list, and only returns the iterator object in reverse order
    4,random.shuffle() random sort

>>> list = [20,30,10,50]
>>> list
[20, 30, 10, 50]
>>> list.sort() #order
>>> list
[10, 20, 30, 50]
>>> list.sort(reverse=True) #Reverse order
>>> list
[50, 30, 20, 10]

>>> list1 = [20,10,30,40]
>>> id(list1)
1971808272576
>>> list1 = sorted(list1)
>>> list1
[10, 20, 30, 40]
>>> id(list1)				#Address changed
1971838081408

>>> list1 = [20,10,30,40]
>>> r = reversed(list1)
>>> r
<list_reverseiterator object at 0x000002CBC5736C70>
>>> list(r)
[40, 30, 10, 20]

#It can be used as test data
>>> import random
>>> random.shuffle(list1)
>>> list1
[10, 40, 30, 20]
>>> random.shuffle(list1)
>>> list1
[30, 40, 20, 10]

3. Tuple tuple

3.1 creating tuples

  • Basic syntax creation
  • tuple() create
  • Generator derivation to create tuples

The generator derivation generates neither a list nor a tuple. It returns the generator object. It can only access the element once. The second access is empty and needs to be regenerated.

>>> a = (20,30,40,50)
>>> a
(20, 30, 40, 50)
>>> type(a)
<class 'tuple'>
>>> a = tuple()
>>> a
()
>>> b = tuple("abc")
>>> b
('a', 'b', 'c')

>>> s = (x * 2 for x in range(5))
>>> s
<generator object <genexpr> at 0x000002CBC57143C0>
>>> tuple(s)
(0, 2, 4, 6, 8)
>>> list(s)
[]


>>> s = (x * 2 for x in range(5))
>>> s.__next__()
0
>>> s.__next__()
2
>>> s.__next__()
4
>>> s.__next__()
6
>>> s.__next__()
8
>>> s.__next__()
Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    s.__next__()
StopIteration

3.2 common operations

Similar to a list, you can't use anything that can change tuple elements except add, delete, insert.

A2

typeBelong to sequenceSlicing methodbasic operation Is the element variable
listyesidenticalbe similarvariable
tupleyesidenticalbe similarImmutable

The elements in the list are variable. If list (tuple) indicates that the elements in the list are tuples, the tuples cannot be changed
The elements in the tuple are immutable. If tuple (list) indicates that the elements in the tuple are lists, the elements in the list are mutable.

>>> a = [10,20,(30,40),50]
>>> a
[10, 20, (30, 40), 50]
>>> a[2] = 30
>>> a
[10, 20, 30, 50]

>>> a = [10,20,(30,40),50]
>>> a[2][1] = 50
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    a[2][1] = 50
TypeError: 'tuple' object does not support item assignment

>>> b = (10,20,[30,50],50)
>>> b
(10, 20, [30, 50], 50)
>>> b[2] = 40
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    b[2] = 40
TypeError: 'tuple' object does not support item assignment
>>> b[2][1] = 40
>>> b
(10, 20, [30, 40], 50)
>>> 

Keywords: Python Back-end

Added by russian_god on Sat, 01 Jan 2022 16:38:06 +0200