列表
1. 列表也可以嵌套在其他列表中。
number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1])
print(things[2])
print(things[2][2])
结果:
0
[1, 2, 3]
3
2. 引用超出列表值的索引范围将导致 IndexError 错误。
str = "Hello world!"
print(str[6])
结果:
w
3. 列表中某个索引处的元素值可以被重新分配。
nums = [7, 7, 7, 7, 7]
nums[2] = 5
print(nums)
结果:
[7,7,5,7,7]
4. 列表可以像字符串一样添加和相乘。
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3)
结果:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
5. 要查找某个值是否在列表中,可以使用 in 运算符。如果值在列表中出现一次或多次,则返回 True,否则返回 False。
words = ["spam", "egg", "spam", "sausage"]
print("spam" in words)
print("egg" in words)
print("tomato" in words)
结果:
True
True
False
6. 要某个值是否不在列表中,可以使用 not 操作符:
nums