What are Lists?
Lists are Python's most versatile data container. They let you store multiple items together inside square brackets [] in a specific order.
Think of a list like:
- A shopping list (
milk,eggs,bread) - A to-do list (
tasks in order) - A playlist (
songs in sequence)
1. Visual Representation of a List & Indexing
A Python List holds items in an ordered sequence. Each item gets an Index position starting from 0.
5
"Six"
2
8.2
0
1
2
3
2. Creating Lists
You create a list by placing items separated by commas inside square brackets []:
# An empty list
shopping_cart = []
# A list of text strings
fruits = ["apple", "banana", "orange"]
# A list of numbers
scores = [95, 88, 72, 100]
# You can mix different data types in the same list!
mixed_items = [5, "Six", 2, 8.2]
3. Accessing Items by Index
Just like strings, every item in a list has a numbered position starting from 0:
fruits = ["apple", "banana", "orange"]
# Grab the first item
print(fruits[0]) # Output: apple
# Grab the second item
print(fruits[1]) # Output: banana
# Grab the last item using negative indexing
print(fruits[-1]) # Output: orange
4. Changing Items inside a List (Mutability)
Unlike strings, lists can be changed after you create them! You can replace any item by assigning a new value to its index position:
fruits = ["apple", "banana", "orange"]
# Replace "apple" with "mango"
fruits[0] = "mango"
print(fruits) # Output: ['mango', 'banana', 'orange']
5. Slicing a List
You can extract a smaller sub-list using a colon [start:stop]:
numbers = [10, 20, 30, 40, 50]
# Grab items from index 1 up to index 3
print(numbers[1:4]) # Output: [20, 30, 40]
6. Checking if an Item Exists (in)
You can easily check if a specific item is inside your list using the in keyword:
fruits = ["apple", "banana", "orange"]
if "banana" in fruits:
print("Yes, banana is in the shopping list!")
Quick Summary
- List Definition: An ordered, mutable collection created with square brackets
[...]. - Mixed Data Types: Lists can store any combination of strings, numbers, booleans, or nested lists.
- Indexing & Slicing: Supports zero-based positive indexing (
list[0]), negative indexing (list[-1]), and slicing (list[start:stop]). - Mutability: Elements inside a list can be modified directly in place without creating a new list.
What's Next?
Now let's explore all the essential List Methods for adding, removing, searching, and sorting items in the next lesson!