This is the fifth day of my participation in Gwen Challenge

“This article has participated in the weekend learning plan, click to see details”

1. Basic introduction

1.1 the sequence

Sequences are the most basic data structures in Python. A sequence is a form of data storage used to store a series of data.

In memory, a sequence is a contiguous chunk of memory used to store multiple values. Like a sequence of integers [10,20,30,40]

Each element in the sequence is assigned a number – its position, or index. The first index is 0, the second index is 1, and so on.

1.2 list

List: Used to store any number of data sets of any type.

A list is a built-in mutable sequence, an ordered contiguous memory space containing multiple elements. Standard syntax for list definitions:

A =,20,30,40 [10]Copy the code

10, 20, 30 and 40 are called the elements of list A.

The elements in the list can be different and can be of any type. For example: a = [10,20,” ABC “,True,[]]

2. List memory distribution

2.1 Creating a List
Print (id(a)) # 4376650528 print(ID (a[0])) # 10--4527943632 print(ID (a[1])) # 10--4527943632 print(ID (a[1])) # 20--4527943952 print(id(a[2])) # 30--4527944272 print(id(a[3])) # 40--4527944592Copy the code

2.2 Adding elements to a list
  • Append () or extend() is used to add elements. Add elements at the end of the list

As the list adds elements, it automatically manages memory, reducing the programmer’s burden. But list elements move around a lot, which is inefficient, so adding them at the end is generally recommended.

Print (a) # [10,20,30,40] print(a) # [10,20,30,40] print(a) # [10,20,30,40] print(a) # [10,20,30,40]  print(id(a)) #4376650528Copy the code

Local PC Running results:

Lists are mutable data types, with fixed addresses and mutable values. Therefore, the address remains the same after the new value is added.

  • Use the insert() function to specify any place to insert elements
Print (a) # [10,20,50,30,40] print(id(a)) # 4376650528Copy the code

50 is referenced at index 2

  1. Python allocates 8 Spaces for lists in internal memory.
  2. In eight memory Spaces, traverses index 2, referencing the object 50
  3. Subsequent indexes 3 and 4 each step back

Eight memory Spaces are allocated but the list is actually used to store elements and only five of them are used for inserts in order n time

2.3 Deleting elements from the list
  • Pop() time complexity is O(1)

The pop () method removes and returns the element at the specified location, or defaults if no location is specified

# define a list a = [10,20,30,40]Copy the code

The pop () method removes and returns the element at the specified location, or defaults if no location is specified

2.4 Declare a TWO-DIMENSIONAL list
# define a list of student = [[" TOM ", 12], [11] "ANNE,", [" Bob ", 8], [" Jon ", 9]] # 2 d print list print (student)Copy the code

Result run: