Introduction to Lists in Python
What is a List?
A list in Python is a collection of ordered, mutable, and heterogeneous elements. This means:
- Ordered ? Items have a fixed sequence.
- Mutable ? You can change, add, or remove elements.
- Heterogeneous ? A list can contain different data types (strings, numbers, booleans, even other lists!).
Lists are one of Python’s most powerful and flexible data structures. They allow you to store multiple values in a single variable.
Creating a List
To create a list, use square brackets [ ]
, separating elements with commas.
# Example of a list
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40]
mixed = [1, "hello", True, 3.5]
Accessing Elements in a List
You can access list items using indexing. In Python, indexing starts from 0
.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: cherry
Negative Indexing
You can also use negative indexes to access elements from the end of the list.
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana
Modifying a List
Since lists are mutable, we can modify elements using their index.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
List Length
To find the number of items in a list, use the len()
function.
print(len(fruits)) # Output: 3
Checking if an Item Exists in a List
Use the in
keyword to check for the presence of an item.
print("banana" in fruits) # Output: False
print("orange" in fruits) # Output: True
Exercise: Try It Yourself!
- Create a list of your favorite movies.
- Print the first and last movie from the list using both positive and negative indexing.
- Modify the second item in the list.
- Check if a specific movie is in the list.