Lists are ordered collections
index从0开始
-1表示最后一个元素,-2表示倒数第二个,以此类推
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
Changing, Adding, and Removing Elements
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# 修改
motorcycles[0] = 'ducati'
print(motorcycles)
# 加到末尾
motorcycles.append('ducati')
print(motorcycles)
# 插入
motorcycles.insert(2, 'hhhh')
print(motorcycles)
# 从指定index移除
del motorcycles[2]
print(motorcycles)
# 从末尾移除,并得到移除的值
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
# 从指定位置pop
popped_motorcycle = motorcycles.pop(1)
print(motorcycles)
print(popped_motorcycle)
# 删除指定值,remove只会删除第一个搜索到的值
motorcycles = ['honda', 'yamaha', 'suzuki','honda']
motorcycles.remove('honda')
print(motorcycles)
Organizing a list
# sort按字母排序,改变自身
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
# sorted不改变自身
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))
print(sorted(cars, reverse=True))
print(cars)
# 反转
cars.reverse()
print(cars)
# length
print(len(cars))
不允许的操作
python不允许给现有索引以外的范围赋值,而JS可以
cars = ['suzuki', 'BYD']
cars[100] = 'qin' # Error list assignment index out of range