Accessing List Elements
Part of the Fundamentals section of Coddy's Python journey — lesson 54 of 77.
In Python, we use lists to store multiple values in a single variable. Each value in a list is called an element, and each element has an index. The indices start from 0 to the length of the list minus one.
For example take a look at the next list:
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']- Element
ais at index 0 - Element
bis at index 1 - ...
- Element
gis at index 6
To access an element of a list, we can use its index within square brackets. For example, to access the first element of a list named my_list, we would use my_list[0].
Here's an example:
my_list = [10, 20, 30, 40, 50]
element = my_list[2]The variable element will hold the value 30 because it access the third element (which has an index of 2).
Challenge
EasyCreate a function named values that receives a list as an argument and prints all of the items in the list one after the other.
For example, if the list is [1, 3, 5, 7], the output should be:
1
3
5
7
Important: The list is already provided to the function as the parameter lst. You don't need to read input or create the list — it is already passed as an argument when the function is called. This means inside your function, lst refers to the list you need to iterate through. You don't need to call the function — it is called automatically.
To iterate over a list and print each element, use the len() function inside the range() function:
def values(lst):
for i in range(len(lst)):
print(lst[i])This way, i will iterate from 0 to len(lst) (not including), which covers exactly all of the list indices. lst[i] accesses the element at index i, and print() displays it on its own line.
Cheat sheet
In Python, lists store multiple values in a single variable:
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']List elements are accessed by index, starting from 0:
element = my_list[2] # Accesses the third element (30)To iterate over a list:
for i in range(len(my_list)):
my_list[i] # Access each elementThe len() function returns the length of the list.
Try it yourself
def values(lst):
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input11Lists Basics
Declaring a ListAccessing List ElementsModifying ListsList MethodsRecap - Product ListRecap - Reversed ListTuple3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2