<Python Lists and Tuples>——《Python》

Table of contents

1. list

1.1 The concept of a list

1.2 Create list 

1.3 Access subscript

1.4 Slicing operation

1.5 Traversing List Elements

1.6 New elements

1.7 Finding elements

1.8 Delete elements

1.9 Connection list

2. Tuples


1. list

1.1 The concept of a list

In programming, it is often necessary to use variables to store/represent data.
If the number of data that needs to be expressed in the code is relatively small, we can directly create multiple variables.
num1 = 10
num2 = 20
num3 = 30
......
But sometimes, the code needs to represent a lot of data, and you don’t even know how many data to represent. At this time, you need to use a list.
  • Lists are a way for programmers to represent/save data in batches in code.
  • Compared with lists, tuples are very similar, except that which elements are placed in the list can be modified and adjusted, and the elements placed in the tuple are set when the tuple is created, and cannot be modified and adjusted.

1.2 Create list 

  • There are two main ways to create a list. [ ] means an empty list

alist = [ ]
alist = list()
print(type(alist))

Because list itself is a built-in function in Python, it is not appropriate to use list as a variable name, so it is named alist.

#创建列表
#1.直接使用字面值来创建
#   []就表示一个空的列表
a = []
print(type(a))

#2.使用list() 来创建
b = list()
print(type(b))

 

  • If you need to set the initial value inside, you can directly write it in [ ].

You can use print directly to print the contents of the elements in the list.

alist = [1, 2, 3, 4]
print(alist)

  • The elements stored in the list are allowed to be of different types. (This is quite different from C++ Java).
alist = [1, 'hello', True]
print(alist)

 

1.3 Access subscript

  • Any element in the list can be accessed through the subscript access operator [ ].
We call the numbers filled in [ ] subscripts or indexes.
alist = [1, 2, 3, 4]
print(alist[2])
Note: The subscript starts counting from 0, so the subscript is 2, which corresponds to the element 3.

  • Not only can the content of the element be read through the subscript, but also the value of the element can be modified.
alist = [1, 2, 3, 4]
alist[2] = 100
print(alist)

  • If the subscript is outside the valid range of the list, an exception will be thrown.
alist = [1, 2, 3, 4]
print(alist[100])
  • Because the subscript starts from 0, the effective range of the subscript is [0, list length - 1]. Use the len function to get the number of elements in the list.
alist = [1, 2, 3, 4]
print(len(alist))
  • The subscript can take a negative number. It means "the penultimate element"

 

#Python中的下标,其实还可以写成负数
#例如:-1 <==> len(a)-1
a = [1, 2, 3, 4]
print(a[len(a)-1])
print(a[-1])

 

 

alist = [1, 2, 3, 4]
print(alist[3])
print(alist[-1])
alist[-1] is equivalent to alist[len(alist) - 1]

 

1.4 Slicing operation

The subscript operation is to take out the first element in it at a time.
By slicing, a group of continuous elements is taken out at a time, which is equivalent to getting a sublist
  • Use [ : ] for slice operations
alist = [1, 2, 3, 4]
print(alist[1:3])
The 1:3 in alist[1:3] means [1, 3) such a closed-before-open-back interval composed of subscripts .
That is, it starts from the element with subscript 1 (2) and ends with the element with subscript 3 (4), but does not include the element with subscript 3.
So the final result is only 2, 3.
  • Front and back boundaries can be omitted in slice operations
alist = [1, 2, 3, 4]
print(alist[1:])        # 省略后边界, 表示获取到列表末尾
print(alist[:-1])       # 省略前边界, 表示从列表开头获取
print(alist[:])         # 省略两个边界, 表示获取到整个列表.

  • The slicing operation can also specify the "step size", that is, "how many steps to increment the subscript after each element is accessed"
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(alist[::1])
print(alist[::2])
print(alist[::3])
print(alist[::5])
  • The step size specified by the slicing operation can also be a negative number, at this time, the elements are fetched from the back to the front. It means "after each element is accessed, the subscript will be decremented by a few steps"
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(alist[::1])
print(alist[::2])
print(alist[::3])
print(alist[1:-1:2])
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(alist[::-1])
print(alist[::-2])
print(alist[::-3])
print(alist[::-5])

 

  • If the number filled in the slice is out of bounds, there will be no negative effect. Only the elements that meet the conditions will be obtained as much as possible
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a[1:100])

 

alist = [1, 2, 3, 4]
print(alist[100:200])

 

1.5 Traversing List Elements

"Traversing" refers to taking out elements one by one, and then processing them separately.

 

(1) The easiest way is to use a for loop

alist = [1, 2, 3, 4]
for elem in alist:
    print(elem)

elem is equivalent to a temporary variable.

(2) Use for to generate subscripts according to the range, and press the subscript to access

alist = [1, 2, 3, 4]
for i in range(0, len(alist)):
    print(alist[i])
a = [1, 2, 3, 4]
for i in range(0, len(a)):
        a[i] = a[i] + 10

print(a)

Note: When modifying list values:

  • elem is a temporary variable, this modification is equivalent to overwriting the value in the temporary variable, and the value in the list cannot be modified.
  • Using coordinate access is actually modifying in the original space. Can be modified.

(3) Use the while loop to manually control the change of the subscript

alist = [1, 2, 3, 4]
i = 0
while i < len(alist):
    print(alist[i])
    i += 1

 

1.6 New elements

  • Use the append method to insert an element at the end of the list (end insertion).
alist = [1, 2, 3, 4]
alist.append('hello')
print(alist)
  • Use the insert method to insert an element at any position

The first parameter of insert indicates the subscript of the element to be inserted.

alist = [1, 2, 3, 4]
alist.insert(1, 'hello')
print(alist)
What is a "method":
A method is actually a function. It's just that a function exists independently, while a method often has to be attached to an "object".
Like the above code alist.append, append is attached to alist, which is equivalent to "perform tail insertion operation on the list of alist".

1.7 Finding elements

  • Use the in operator to determine whether an element exists in the list. The return value is a Boolean type.
alist = [1, 2, 3, 4]
print(2 in alist)
print(10 in alist)
print(2 not in alist)
print(10 not in alist)

  • Use the index method to find the index of the element in the list. The return value is an integer. If the element does not exist, an exception will be thrown.
alist = [1, 2, 3, 4]
print(alist.index(2))
print(alist.index(10))

 

 

1.8 Delete elements

  • Use the pop method to remove the last element
alist = [1, 2, 3, 4]
alist.pop()
print(alist)

 

  • pop can also delete elements by subscript
alist = [1, 2, 3, 4]
alist.pop(2)
print(alist)

  • Use the remove method to remove elements by value
alist = [1, 2, 3, 4]
alist.remove(2)
print(alist)

 

a = ['python', 'list',  'group']
print(a)
a.remove('python')
print(a)

 

1.9 Connection list

  • Use + to concatenate two lists together.
The + result here will generate a new list. It will not affect the contents of the old list.

 

a = [1, 2, 3, 4]
b = [5, 6, 7]
print(a + b)
print(b + a)
  • Using the extend method is equivalent to splicing a list to the back of another list.
a.extend(b) is to splice the content in b to the end of a. It will not modify b, but will modify a.
alist = [1, 2, 3, 4]
blist = [5, 6, 7]
alist.extend(blist)
print(alist)
print(blist)

 Note:

extend() compares with +=:

a = [1, 2, 3, 4]
b = [5, 6, 7]
#a.extend(b) 则是直接把b的内容拼接到了a的后面   ——>高效
a += b  #  a += b <==> a = a + b            ——>低效
print(a)
print(b)

 

2. Tuples

The function of tuple is basically the same as that of list.
(1) Tuples are represented by ( )
atuple = ( )
atuple = tuple()
a = ()
print(type(a))
b = tuple()
print(type(b))
(2) When creating a tuple, specify the initial value
#创建元组的时候,指定初始值
a = (1, 2, 3, 4)
print(a)

(3) The elements in the tuple can also be of any type

#元组中的元素也可以使任意类型的
a = (1, 'python', True, [])
print(a)

(4) Access the elements in the tuple through the subscript, the subscript also starts from 0 and ends at len-1

 
#通过下标来访问元组中的元素,下标是也是从0开始,到len-1 结束
a = (1, 2, 3, 4)
print(a[1])
print(a[-1])
print(a[100])

(5) Get a part of the tuple by slicing

#通过切片来获取元组中的一个部分
a = (1, 2, 3, 4)
print(a[1:3])

(6) Use for loop and other methods to traverse elements

#使用for循环等方式来进行遍历元素
a = (1, 2, 3, 4)
for elem in a:
    print(elem)

(7) Use in to determine whether the element exists, and use index to find the subscript of the element

#使用in判断元素是否存在,使用index查找元素的下标
a = (1, 2, 3, 4)
print(3 in a)
print(a.index(3))

 (8) Use + to splice tuples

#使用 + 拼接元组
a = (1, 2, 3, 4)
b = (5, 6, 7)
print(b + a)

 Note:

#元组不支持修改值
a = (1, 2, 3, 4)
a[0] = 9   #error

 

Tuples cannot modify the elements inside, but lists can modify the elements inside !
Therefore, like read operations, such as accessing subscripts, slicing, traversing, in, index, +, etc., tuples are also supported.
However, like write operations, such as modifying elements, adding elements, deleting elements, extending, etc., tuples cannot support.
Also, tuples are often the default collection type in Python. For example, when a function returns multiple values.
def getPoint():
    return 10, 20
result = getPoint()
print(type(result))
The type of result here is actually a tuple.

 

Here comes the question, since there are already lists, why do we need tuples?
Compared with lists, tuples have two advantages:
  • You have a list, and now you need to call a function to do some processing. But you are not sure whether this function will mess up your list data. Then it is much safer to pass a tuple at this time.
  • The dictionary we will talk about soon is a key-value pair structure. It is required that the key of the dictionary must be a "hashable object" (the dictionary is essentially a hash table). The premise of a hashable object is immutable. Therefore, tuples can as keys in dictionaries, but not lists.
summary
Lists and tuples are the most commonly used types in daily development. The core operation is to press the index according to [ ].
In the scenario where a "sequence" needs to be represented, lists and tuples can be considered.
If elements do not need to change, tuples are preferred.
If the element needs to change, the list is preferred.

Guess you like

Origin blog.csdn.net/m0_57859086/article/details/128737544