List traversal
It can for
be traversed using
numbers = [1,2,3,4,5,6]
for i in numbers:
print(i)
Create a list of values
range function
- Start from the first value to the end of the last value, but cannot get the last number.
- If the
range
function has a third parameter, it means the increment of the value
#从数字1开始,到数字9结束
numbers = list(range(1,10))
#从数字1开始,到数字9结束,每次数字增加2
numbers = list(range,1,10,2)
Slice of list
Use :
to slice lists in Python .
- If
:
there are numbers before and after, it means that it starts from the preceding subscript and ends with the following subscript. - If
:
there is only a number in front, it means starting from the previous subscript and ending at the end of the list. - If
:
there is only a number after it, it means that it starts from the head and ends with the subscript at the back. - If the
:
first number is negative, it means that the data is taken from the back to the front. - If there
:
are no numbers before and after, it means that the entire list is
numbers = []
#初始化一个新的数字列表
for i in range(1,101):
numbers.append(i)
#从2号下标开始,到9号下标结束,将其结果赋值为一个新的列表
number = numbers[2:10]
#从0号下标开始,到9号下标结束
number = numbers[:10]
#从10号下标开始,到末尾结束
number = numbers[10:]
#从后往前读取10个数字
number = numbers[-10:]
#将整个列表进行赋值
number = numbers[:]
Tuple
In Python, an immutable list is called a tuple. The essence of a tuple is a list, but the content of its data elements is immutable. Tuples are written in parentheses, and the elements ,
are separated by. At the same time, the types of the elements in the tuples can also be different.
Definition of tuple
Used in Python ()
to define a tuple.
number = () #定义一个空元组
number = (20,)#定义一个只含有一个元素的元组
number = (1,2,3,4,5)
Note: If you only define a tuple with one element, you need to add a comma, if you don’t add it, the compiler will consider it to be another type
Traversal of tuples
Tuples support traversal in the form of subscripts, and we can also traverse in for
the form of loops.
#按照下标的形式进行遍历
number[1]
for i in number:
print(i)
Slice of tuple
numbers = (1,2,3,4,5,6)
number = numbers[1:3]
The difference between a list and a tuple
- The main difference between a list and a tuple is that the list supports variable data, and we can modify the data in the list. The data in the tuple is fixed.
- The definition is different: the list is
[]
, and the tuple is()
defined. - Both lists and tuples can be sliced.
- There is no
append、pop
equivalent function in the tuple .