Managing Multiple Items with a List
In Python, a List is a data type that allows you to manage multiple values together. You can use lists to manage things like a list of event attendees or items in a shopping cart.
Lists are ordered and each element can be accessed using an index that starts from 0.
How can we create a list?
Lists are created by placing multiple values, separated by commas (,), within square brackets ([ ]).
The values inside the list can include various data types like numbers, strings, etc.
# List made up of numbers numbers = [1, 2, 3, 4, 5] # List made up of strings fruits = ["apple", "banana", "cherry"]
A list can also contain another list.
This is called a nested list and is useful for representing more complex data structures like matrices.
# Nested list matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
Accessing elements in a list and modifying their values
Each element in a list is accessed using its numeric index.
Indexing starts at 0, meaning the first element has an index of 0, the second element has an index of 1, the third element has an index of 2, and so on.
fruits = ["apple", "banana", "cherry"] # Prints "apple" print(fruits[0]) # Prints "cherry" print(fruits[2]) # Modify an element in the list fruits[1] = "blueberry" # Prints ["apple", "blueberry", "cherry"] print(fruits)
You can also access elements from the end of the list by using negative indices.
fruits = ["apple", "banana", "cherry"] # Prints "cherry" print(fruits[-1]) # Prints "banana" print(fruits[-2])
The index of the first element in the list is 1.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result