7 min read
ā¢Question 5 of 41easyLists in Python
Understanding Python lists.
What You'll Learn
- How lists work in Python
- All list methods and operations
- List comprehensions and advanced techniques
- Common interview patterns with lists
- Performance considerations
Understanding Python Lists
Lists are Python's most versatile data structure - ordered, mutable collections that can hold items of any type. Think of them as dynamic arrays that can grow and shrink.
Lists are defined by square brackets [] and are essential for:
- Storing collections of data
- Iterating through sequences
- Implementing stacks and queues
- Data manipulation and transformation
Creating Lists
code.pyPython
# Empty list - two ways
empty1 = []
empty2 = list()
# List with items
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
# Mixed types (allowed, but not recommended)
mixed = [1, "hello", 3.14, True, None]
# Nested lists (2D array)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# From other iterables
from_string = list("hello") # ['h', 'e', 'l', 'l', 'o']
from_range = list(range(5)) # [0, 1, 2, 3, 4]
# Repeat elements
zeros = [0] * 5 # [0, 0, 0, 0, 0]Accessing Elements
code.pyPython
fruits = ["apple", "banana", "cherry", "date"]
# 0 1 2 3 (positive)
# -4 -3 -2 -1 (negative)
# Indexing
fruits[0] # "apple" (first)
fruits[-1] # "date" (last)
fruits[2] # "cherry"
# Slicing [start:end:step]
fruits[1:3] # ["banana", "cherry"]
fruits[:2] # ["apple", "banana"]
fruits[2:] # ["cherry", "date"]
fruits[::2] # ["apple", "cherry"] (every 2nd)
fruits[::-1] # Reversed list
# Nested access
matrix = [[1, 2], [3, 4]]
matrix[0][1] # 2Modifying Lists
code.pyPython
nums = [1, 2, 3]
# Change element
nums[0] = 10 # [10, 2, 3]
# Add elements
nums.append(4) # [10, 2, 3, 4] - add to end
nums.insert(0, 0) # [0, 10, 2, 3, 4] - add at index
nums.extend([5, 6]) # [0, 10, 2, 3, 4, 5, 6] - add multiple
# Remove elements
nums.pop() # Remove and return last (6)
nums.pop(0) # Remove and return at index (0)
nums.remove(10) # Remove first occurrence of value
del nums[0] # Delete by index
nums.clear() # Remove all elements
# Difference: append vs extend
a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4]) # [1, 2, 3, 4]List Methods
| Method | Description | Returns |
|---|---|---|
append(x) | Add x to end | None |
extend(iter) | Add all items from iter | None |
insert(i, x) | Insert x at position i | None |
remove(x) | Remove first x | None |
pop([i]) | Remove and return item at i | item |
clear() | Remove all items | None |
index(x) | Find index of first x | int |
count(x) | Count occurrences of x | int |
sort() | Sort in place | None |
reverse() | Reverse in place | None |
copy() | Shallow copy | list |
code.pyPython
nums = [3, 1, 4, 1, 5, 9, 2, 6]
# Searching
nums.index(4) # 2 (first occurrence)
nums.count(1) # 2 (occurrences)
5 in nums # True (membership)
# Sorting
nums.sort() # [1, 1, 2, 3, 4, 5, 6, 9]
nums.sort(reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1]
# sorted() returns new list (original unchanged)
original = [3, 1, 2]
new_sorted = sorted(original) # [1, 2, 3]
# Custom sort
words = ["banana", "pie", "apple"]
words.sort(key=len) # ['pie', 'apple', 'banana']List Comprehension
Powerful, Pythonic way to create lists:
code.pyPython
# Basic syntax: [expression for item in iterable]
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]
# With condition: [expr for item in iter if condition]
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# With if-else
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
# ['even', 'odd', 'even', 'odd', 'even']
# Nested loops
pairs = [(x, y) for x in range(3) for y in range(3)]
# [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]
# Flatten nested list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]Copying Lists
code.pyPython
# Shallow copy (only copies references)
original = [1, [2, 3]]
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
# Deep copy (copies nested objects too)
import copy
deep = copy.deepcopy(original)
# Why it matters
original = [1, [2, 3]]
shallow = original.copy()
shallow[1][0] = 99
print(original) # [1, [99, 3]] - nested list changed!
deep = copy.deepcopy([1, [2, 3]])
deep[1][0] = 99
print(original) # [1, [99, 3]] - original unchangedCommon Operations
code.pyPython
nums = [1, 2, 3, 4, 5]
# Length
len(nums) # 5
# Sum, min, max
sum(nums) # 15
min(nums) # 1
max(nums) # 5
# Check if all/any
all([True, True, False]) # False
any([True, False, False]) # True
# Enumerate (index + value)
for i, val in enumerate(nums):
print(f"{i}: {val}")
# Zip (parallel iteration)
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age}")Interview Tip
When asked about Python lists:
- Lists are mutable and ordered
- Use list comprehensions for concise code
- Know the difference between
appendandextend - Understand shallow vs deep copy
- Time complexity: O(1) append, O(n) insert/remove at beginning
- Use
collections.dequefor efficient left operations