Lesson 35 +10 XP

Access and Change List Items

Access and Change List Items

Lists support ranged access and in-place changes.

Access by index

thislist = ["apple", "banana", "cherry"]
print(thislist[1])  # banana

Range of indexes (slicing)

print(thislist[1:3])  # ['banana', 'cherry']
print(thislist[:2])   # ['apple', 'banana']
print(thislist[1:])   # ['banana', 'cherry']

Negative ranges

print(thislist[-3:-1])  # ['apple', 'banana']

Check if item exists

if "apple" in thislist:
    print("Yes, apple is in the list")

Change a single item

thislist[1] = "blackcurrant"
print(thislist)  # ['apple', 'blackcurrant', 'cherry']

Change a range of items

thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)  # ['apple', 'blackcurrant', 'watermelon']

Insert without replacing

insert() adds an item at an index and shifts the rest:

thislist.insert(1, "blueberry")

TL;DR

  • Index with list[n]; slice with list[a:b].
  • in checks whether an item exists.
  • list[i] = value changes an item.
  • insert(i, v) adds without replacing.