3.1.4.2 Lists - collections of data | Indexing
Indexing lists
How do you change the value of a chosen element in the list?
Let's assign a new value of
111
to the first element in the list. We do it this way:numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list content
numbers[0] = 111
print("New list content: ", numbers) # current list content
And now we want the value of the fifth element to be copied to the second element - can you guess how to do it?
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # printing original list content
numbers[0] = 111
print("\nPrevious list content:", numbers) # printing previous list content
numbers[1] = numbers[4] # copying value of the fifth element to the second
print("New list content:", numbers) # printing current list content
The value inside the brackets which selects one element of the list is called an index, while the operation of selecting an element from the list is known as indexing.
We're going to use the
print()
function to print the list content each time we make the changes. This will help us follow each step more carefully and see what's going on after a particular list modification.
Note: all the indices used so far are literals. Their values are fixed at runtime, but any expression can be the index, too. This opens up lots of possibilities.
Comments
Post a Comment