Uploaded by Ben Toyne

Textbook

advertisement
For example, let’s say we have a list of motorcycles, and the first item in
the list is 'honda'. How would we change the value of this first item?
motorcycles.py u motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
v motorcycles[0] = 'ducati'
print(motorcycles)
The code at u defines the original list, with 'honda' as the first element.
The code at v changes the value of the first item to 'ducati'. The output
shows that the first item has indeed been changed, and the rest of the list
stays the same:
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
You can change the value of any item in a list, not just the first item.
Adding Elements to a List
You might want to add a new element to a list for many reasons. For
example, you might want to make new aliens appear in a game, add new
data to a visualization, or add new registered users to a website you’ve
built. Python provides several ways to add new data to existing lists.
Appending Elements to the End of a List
The simplest way to add a new element to a list is to append the item to the
list. When you append an item to a list, the new element is added to the end
of the list. Using the same list we had in the previous example, we’ll add the
new element 'ducati' to the end of the list:
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
u motorcycles.append('ducati')
print(motorcycles)
The append() method at u adds 'ducati' to the end of the list without
affecting any of the other elements in the list:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
Introducing Lists 37
Download