List Indexes
Pick single items out of a list.
1fruits = ["apple", "banana", "cherry"]
2print(fruits[0])
3print(fruits[-1])
$ python3 main.py
apple
cherry
Every line, explained
fruits = ["apple", "banana", "cherry"]- A list stores several values in one variable. The values go between square brackets, separated by commas. Lists are one of Python's favourite tools, and unlike some languages, you can print one directly and see its contents.
print(fruits[0])- You get one item from a list using its index (position) in square brackets, and counting starts at 0, not 1! So fruits[0] is "apple", fruits[1] is "banana" and fruits[2] is "cherry".
print(fruits[-1])- A neat Python trick: negative indexes count from the END of the list. fruits[-1] is the last item, fruits[-2] the one before it. No need to know how long the list is!