Lesson 35 +10 XP

Access and Change List Items

Lists support ranged access and in-place changes.

Access by index


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

### banana

Range of indexes (slicing)


python
print(thislist[1:3])

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

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

### ['banana', 'cherry']

Negative ranges


python
print(thislist[-3:-1])

### ['apple', 'banana']

Check if item exists


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

Change a single item


python
thislist[1] = "blackcurrant"
print(thislist)

### ['apple', 'blackcurrant', 'cherry']

Change a range of items


python
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

### ['apple', 'blackcurrant', 'watermelon']

Insert without replacing

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


python
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.