
Syntax: List Indexing and In Keyword
Searching and retrieving values from Python lists.
In Python, lists store multiple items in a single variable. List items are ordered, changeable, and allow duplicate values. List items are indexed, with the first item having an index of 0.
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(days[0])
print(days[3])
> "Monday"
> "Thursday"
Python also allows negative indexing, where -1 refers to the last item, -2 refers to the second last item, and so on.
print(days[-1])
print(days[-2])
> "Friday"
> "Thursday"
The 'in' keyword can be used to check if an item exists in the list.
if "Wednesday" in days:
print("Yes, 'Wednesday' is in the list days.")
> "Yes, 'Wednesday' is in the list days."
Practice: Retrieve Item at a Specific Index
-
Create a list named
fruitsand assign it the values"Apple", "Banana", "Cherry", "Dragon Fruit", "Elderberry". -
Print the item at index
2from the list.
Run your code and confirm that the output is "Cherry".
HINT*: Click here for a hint
> "Cherry"
SOLUTION*: Click here for an example solution
fruits = ["Apple", "Banana", "Cherry", "Dragon Fruit", "Elderberry"]
print(fruits[2])
Practice: Check if an Item Exists
-
Create a list named
fruitsand assign it the values"Apple", "Banana", "Cherry", "Dragon Fruit", "Elderberry"if you haven't already. -
Use the 'in' keyword to check if
"Banana"is in thefruitslist and print the result. -
Use the 'in' keyword to check if
"Grapes"is in thefruitslist and print the result.
Run your code and confirm that the output is True for "Banana" and False for "Grapes".
HINT*: Click here for a hint
> True
> False
SOLUTION*: Click here for an example solution
fruits = ["Apple", "Banana", "Cherry", "Dragon Fruit", "Elderberry"]
print("Banana" in fruits)
print("Grapes" in fruits)
Good job! Your understanding of lists, their indexing, and the 'in' keyword in Python is improving. This knowledge is very useful when dealing with sequential data in Python.