Lists are ordered collections
index从0开始
-1表示最后一个元素,-2表示倒数第二个,以此类推

  1. bicycles = ['trek', 'cannondale', 'redline', 'specialized']
  2. message = f"My first bicycle was a {bicycles[0].title()}."
  3. print(message)

Changing, Adding, and Removing Elements

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. print(motorcycles)
  3. # 修改
  4. motorcycles[0] = 'ducati'
  5. print(motorcycles)
  6. # 加到末尾
  7. motorcycles.append('ducati')
  8. print(motorcycles)
  9. # 插入
  10. motorcycles.insert(2, 'hhhh')
  11. print(motorcycles)
  12. # 从指定index移除
  13. del motorcycles[2]
  14. print(motorcycles)
  15. # 从末尾移除,并得到移除的值
  16. popped_motorcycle = motorcycles.pop()
  17. print(motorcycles)
  18. print(popped_motorcycle)
  19. # 从指定位置pop
  20. popped_motorcycle = motorcycles.pop(1)
  21. print(motorcycles)
  22. print(popped_motorcycle)
  23. # 删除指定值,remove只会删除第一个搜索到的值
  24. motorcycles = ['honda', 'yamaha', 'suzuki','honda']
  25. motorcycles.remove('honda')
  26. print(motorcycles)

Organizing a list

  1. # sort按字母排序,改变自身
  2. cars = ['bmw', 'audi', 'toyota', 'subaru']
  3. cars.sort()
  4. print(cars)
  5. cars = ['bmw', 'audi', 'toyota', 'subaru']
  6. cars.sort(reverse=True)
  7. print(cars)
  8. # sorted不改变自身
  9. cars = ['bmw', 'audi', 'toyota', 'subaru']
  10. print(sorted(cars))
  11. print(sorted(cars, reverse=True))
  12. print(cars)
  13. # 反转
  14. cars.reverse()
  15. print(cars)
  16. # length
  17. print(len(cars))

不允许的操作

python不允许给现有索引以外的范围赋值,而JS可以

  1. cars = ['suzuki', 'BYD']
  2. cars[100] = 'qin' # Error list assignment index out of range