Lecture 03-Introducing List
Lecture 03-Introducing List
Python List
print(bicycles)
● Output:
print(bicycles[0])
● Output: Trek
● Python returns just that element without square brackets or quotation marks.
Accessing elements (Index position 0, not 1)
● Python considers the first item in a list to be at position 0, not position 1. The second item in a
list has an index of 1. You can get any element you want from a list by subtracting one from its
position in the list.
● For instance, to access the fourth item in a list, you request the item at index 3.
● The following asks for the bicycles at index 1 and index 3:
● This code returns the second and fourth bicycles in the list:
cannondale
specialized
Accessing elements (Index position 0, not 1)
● Python has a special syntax for accessing the last element in a list.
● By asking for the item at index -1, Python always returns the last item in the list:
print(bicycles[-1])
● This code returns the value 'specialized'. This syntax is quite useful, because you’ll often want
to access the last items in a list without knowing exactly how long the list is.
● This convention extends to other negative index values as well. The index -2 returns the second
item from the end of the list, the index -3 returns the third item from the end, and so forth.
Using Individual Values from a List
● You can use individual values from a list just as you would any other variable.
● For example, you can use concatenation to create a message based on a value from a list.
● Let’s try pulling the first bicycle from the list and composing a message using that value.
● Output: