bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Python/Foundations
Python•Foundations

Python - Change List Items

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Python - Change List Items?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ = ["apple", "banana", "cherry"]
3Order

Put the learning moves in the order that makes the concept easiest to apply.

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:
To change the value of a specific item, refer to the index number:
Change a Range of Item Values

Change Item Value

To change the value of a specific item, refer to the index number:

Example

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"

print(thislist)

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:

Example

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]

thislist[1:3] = ["blackcurrant", "watermelon"]

print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant",
"watermelon"]
print(thislist)

Note

The length of the list will change when the number of items inserted does not match the number of items replaced.

If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method.

The insert() method inserts an item at the specified index:

Example

thislist = ["apple", "banana", "cherry"]

thislist.insert(2, "watermelon")

print(thislist)

Note

As a result of the example above, the list will now contain 4 items.

Previous

Python - Access List Items

Next

Python - Add List Items