Python Lists Data Structures
List is the most versatile and commonly used data structure. Unlike Arrays in C or Java (which are fixed-size and single-type).
Python Lists are dynamic arrays that can grow, shrink, and hold any type of data.
A list is an ordered collection of items stored in a single variable. Think of it as a specialized container that holds references to objects.
Key Characteristics:
- Ordered: Items have a defined order (0, 1, 2…). Adding new items puts them at the end.
- Mutable: You can change, add, or delete items after the list is created.
- Heterogeneous: A single list can hold Integers, Strings, Booleans, and even other Lists mixed together.
- Dynamic: You don’t need to specify a size. It grows automatically.
- Allow Duplicates:
[1, 1, 1]is perfectly valid.
2. Creating Lists
There are three main ways to create a list.
1. Square Brackets (Most Common)
fruits = ["apple", "banana", "cherry"] mixed = [1, "Hello", 3.14, True] empty = []
2. The list() Constructor
Useful when converting other types (like tuples or strings) into a list.
# Note: Double parentheses are needed if passing a list directly numbers = list((1, 2, 3)) # Converting string to list chars = list("Python") # Output: ['P', 'y', 't', 'h', 'o', 'n']
3. List Comprehension (The “Pro” Way)
Generating a list mathematically.
# Create a list of squares [0, 1, 4, 9, 16] squares = [x**2 for x in range(5)] # Create list using range rangelist = range(1,100)
3. Memory & Performance
Python lists are not actually storing the “data” directly in a row. They store memory addresses (references) pointing to the data objects scattered in memory.
- Dynamic Resizing: When you create a list, Python allocates a block of memory. If you
.append()more items than the block can hold, Python automatically moves the entire list to a larger memory block (usually doubling the size). - Performance:
- Accessing by Index: Fast list(1). Python knows exactly where index 5 is.
- Appending to End: Fast list(1).
- Inserting at Start: Slow list(n). Python must shift every other item to the right to make space.
4. Accessing & Slicing
Indexing
- Positive: 0 is first, 1 is second.
- Negative: -1 is last, -2 is second last.
data = [10, 20, 30, 40] print(data[0]) # 10 print(data[-1]) # 40
Slicing
Syntax: list[start : stop : step]
- Copying a list:
new_list = old_list[:](Fastest way to copy). - Reversing a list:
rev = old_list[::-1].
data = [0, 1, 2, 3, 4, 5, 6] print(data[2:5]) # [2, 3, 4] (Stop index is excluded) print(data[::2]) # [0, 2, 4, 6] (Step 2)
5. Modifying Lists (CRUD Operations)
Adding Elements
| Method | Description | Example |
.append(x) | Adds x to the end. | nums.append(5) |
.insert(i, x) | Adds x at index i. | nums.insert(0, "Start") |
.extend(iter) | Adds multiple items from another list. | nums.extend([6, 7, 8]) |
Difference between
appendvsextend:
a.append([1, 2])→ Adds the list as one item:[... , [1, 2]](Nested).a.extend([1, 2])→ Adds the elements:[... , 1, 2].
Removing Elements
| Method | Description | Example |
.pop(i) | Removes & returns item at index i (default last). | last = nums.pop() |
.remove(x) | Removes the first occurrence of value x. | nums.remove("banana") |
.clear() | Removes all items (Empty list). | nums.clear() |
del list[i] | Deletes item (or slice) from memory. | del nums[0] |
6. Nested Lists (2D Arrays)
Since lists can hold anything, they can hold other lists. This is how Python creates matrices.
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Accessing the number '6' # matrix[row][column] print(matrix[1][2]) # Output: 6
7. List Comprehension
This is a concise syntax to create lists based on existing lists. It is usually faster and more readable than for loops.
Syntax: [expression for item in iterable if condition]
# Traditional Way evens = [] for x in range(10): if x % 2 == 0: evens.append(x) # List Comprehension Way evens = [x for x in range(10) if x % 2 == 0]
8. Copying Lists
Because lists are mutable, assigning one list to another variable does not create a copy. It creates a reference to the same list.
a = [1, 2, 3] b = a # b refers to the SAME list as a b.append(4) print(a) # Output: [1, 2, 3, 4] # (Wait, 'a' changed too!)
How to Copy Correctly:
- Shallow Copy:
b = a.copy()orb = a[:]. (Good for simple lists). - Deep Copy:
import copy; b = copy.deepcopy(a). (Needed for nested lists).
9. Common List Methods Cheat Sheet
| Method | Usage | Description |
index() | ls.index(val) | Returns index of the first item with value val. |
count() | ls.count(val) | Returns how many times val appears. |
sort() | ls.sort() | Sorts list in-place (Modifies original). |
| ls.reverse() | Reverses list in-place. |
min() | min(ls) | Returns smallest item. |
max() | max(ls) | Returns largest item. |
sum() | sum(ls) | Returns sum of all numbers. |
list.sort()changes the actual list. If you want to keep the original list and get a new sorted version, use the functionsorted(list).