What is a List?¶
In Python, a List is an ordered and mutable data container, like a “basket” that can hold various items. You can store numbers, strings, or even other lists in it, and you can modify, add, or delete elements at any time. Lists are represented by square brackets [], with elements separated by commas ,.
I. Creating a List¶
Creating a list is straightforward: simply enclose elements in square brackets []. Elements can be of different types (numbers, strings, booleans, etc.), and you can even create an empty list.
Example 1: Basic Lists
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "cherry"]
# Mixed-type list (supports different element types)
mixed = [10, "hello", True, 3.14]
# Empty list (no elements initially)
empty_list = []
II. Indexing: Accessing List Elements¶
List elements are ordered, and we access individual elements using their “index” (like a house number). Python uses 0-based indexing (not 1-based!). The last element can be accessed with -1 (second-to-last with -2), and so on.
Example 2: Basic Indexing
fruits = ["apple", "banana", "cherry", "date"]
# Access the first element (index 0)
print(fruits[0]) # Output: apple
# Access the last element (index -1)
print(fruits[-1]) # Output: date
# Access the second-to-last element (index -2)
print(fruits[-2]) # Output: cherry
Note: Accessing an index out of range (e.g., fruits[4] for a list with 4 elements) will raise an IndexError.
III. Slicing: Getting a Subset of the List¶
Slicing extracts consecutive elements from a list. The syntax is list[start:end:step]:
- start: Includes the element at this index (default: 0);
- end: Excludes the element at this index (default: list length);
- step: Number of steps to move (default: 1; negative step reverses the order).
Example 3: Basic Slicing
numbers = [0, 1, 2, 3, 4, 5, 6]
# Elements from index 1 to 3 (exclusive of 3)
print(numbers[1:4]) # Output: [1, 2, 3]
# From start to index 5 (exclusive), step 2 (every other element)
print(numbers[:5:2]) # Output: [0, 2, 4]
# Reverse slice (step = -1)
print(numbers[::-1]) # Output: [6, 5, 4, 3, 2, 1, 0]
# Copy the entire list
copied = numbers[:]
print(copied) # Output: [0, 1, 2, 3, 4, 5, 6]
IV. Common List Operations¶
Lists are flexible, supporting add, delete, modify, and check operations. Below are the most common methods:
1. Adding Elements¶
append(): Add one element to the end of the list;insert(): Insert an element at a specific position.
Example 4: Adding Elements
fruits = ["apple", "banana"]
# Append an element to the end
fruits.append("cherry")
print(fruits) # Output: ["apple", "banana", "cherry"]
# Insert an element at index 1
fruits.insert(1, "orange")
print(fruits) # Output: ["apple", "orange", "banana", "cherry"]
2. Deleting Elements¶
remove(): Delete the first occurrence of a value (raises an error if no match exists);pop(): Delete an element by index (default: last element, returns the deleted element);del: Delete elements at a specific position or the entire list.
Example 5: Deleting Elements
fruits = ["apple", "banana", "cherry", "banana"]
# Remove the first "banana" by value
fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry", "banana"]
# Remove by index (delete index 0)
removed = fruits.pop(0)
print(removed) # Output: apple
print(fruits) # Output: ["cherry", "banana"]
# Delete the entire list (via del)
del fruits[0]
print(fruits) # Output: ["banana"]
3. Modifying Elements¶
Directly modify elements by assigning new values to their index.
Example 6: Modifying Elements
numbers = [1, 2, 3]
numbers[1] = 100 # Modify the element at index 1 to 100
print(numbers) # Output: [1, 100, 3]
4. List Length and Checking Elements¶
len(): Get the number of elements in the list;in: Check if an element exists in the list (returnsTrue/False).
Example 7: Length and Existence Check
fruits = ["apple", "banana"]
# Get list length
print(len(fruits)) # Output: 2
# Check if an element exists
print("apple" in fruits) # Output: True
print("orange" in fruits) # Output: False
5. List Concatenation and Repetition¶
+: Concatenate two lists (returns a new list, original lists unchanged);*: Repeat a listntimes (returns a new list);extend(): Add all elements of another list to the end of the current list (modifies the original list).
Example 8: Concatenation and Repetition
list1 = [1, 2]
list2 = [3, 4]
# Concatenate lists
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4]
# Repeat the list 3 times
repeated = list1 * 3
print(repeated) # Output: [1, 2, 1, 2, 1, 2]
# Extend list1 with list2 (modifies list1)
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4]
6. Sorting and Reversing¶
sort(): Sort the list in-place (modifies the original list, ascending order);sorted(): Return a new sorted list (original list unchanged);reverse(): Reverse the list in-place;reversed(): Return a reversed iterator (convert to list withlist()).
Example 9: Sorting and Reversing
numbers = [3, 1, 4, 2]
# Sort in ascending order (in-place)
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
# Sort in descending order (returns a new list)
sorted_desc = sorted(numbers, reverse=True)
print(sorted_desc) # Output: [4, 3, 2, 1]
# Reverse the list (in-place)
numbers.reverse()
print(numbers) # Output: [4, 3, 2, 1]
V. Quick Summary¶
Lists are one of Python’s most fundamental and versatile data structures. Key points to master:
- Creation: Use [] or list();
- Indexing/Slicing: Remember 0-based indexing and the syntax [start:end:step];
- Operations: Familiarize yourself with common methods for adding (append/insert), deleting (remove/pop/del), modifying (index assignment), and checking (len/in).
Practice with real-world scenarios (e.g., to-do lists, student score tracking) to quickly become proficient!