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])
Lessons in this chapter ยท Learning Python-specific Data Types
- 1. Managing Multiple Items with a List
- 2. Smart Ways to Utilize Lists
- 3. Adding/Removing Values to/from a List
- 4. Using Loops with Lists
- 5. Creating Lists Concisely Using List Comprehension
- 6. Fill-in-the-blank quiz
- 7. Immutable Collection of Values, Tuple
- 8. Representative Ways to Use Tuples
- 9. A Data Structure Comprising Keys and Values (Dictionary)
- 10. Efficiently Handling Dictionary Data
- 11. How to Use Dictionaries?
- 12. Multiple-choice quiz
- 13. Coding Quiz - Sorting a List
The index of the first element in the list is 1.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help