Learning

Lists Comprehensive Guide

Lists Comprehensive Guide

Creating Lists

python
# Literal syntax fruits = ['apple', 'banana', 'cherry'] nums = [1, 2, 3, 4, 5] mixed = [1, 'hello', True, 3.14, None] # Constructor empty = list() from_str = list('Python') # ['P', 'y', 't', 'h', 'o', 'n'] # Repetition zeros = [0] * 5 # [0, 0, 0, 0, 0] # Nested (2D) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Accessing & Slicing

python
nums = [10, 20, 30, 40, 50] print(nums[0]) # 10 print(nums[-1]) # 50 print(nums[1:4]) # [20, 30, 40] print(nums[::2]) # [10, 30, 50] # Slicing creates a SHALLOW COPY slice_copy = nums[:] slice_copy[0] = 99 print(nums) # [10, 20, 30, 40, 50] (unchanged!) # 2D access matrix = [[1, 2, 3], [4, 5, 6]] print(matrix[0][1]) # 2

Adding Elements

python
nums = [1, 2, 3] nums.append(4) # [1, 2, 3, 4] (adds ONE item) nums.extend([5, 6]) # [1, 2, 3, 4, 5, 6] (merges iterable) nums.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6] (at index) # ⚠️ Common mistake nums.append([7, 8]) # [0, 1, 2, 3, 4, 5, 6, [7, 8]] (nested!) nums.extend([7, 8]) # Correct way to add multiple elements # Concatenation (creates NEW list) new = nums + [9, 10]

Removing Elements

python
nums = [1, 2, 3, 2, 4, 2] nums.remove(2) # Removes FIRST occurrence → [1, 3, 2, 4, 2] last = nums.pop() # Removes & returns LAST → returns 2, list is [1, 3, 2, 4] at = nums.pop(1) # Removes & returns AT INDEX → returns 3, list is [1, 2, 4] del nums[0] # Deletes by index/slice → [2, 4] nums.clear() # Empties list → [] # Safe removal if 99 in nums: nums.remove(99) # Avoids ValueError

Sorting

python
nums = [3, 1, 4, 1, 5, 9] # sort() — IN-PLACE (modifies original, returns None) nums.sort() print(nums) # [1, 1, 3, 4, 5, 9] nums.sort(reverse=True) print(nums) # [9, 5, 4, 3, 1, 1] # sorted() — RETURNS NEW LIST (original unchanged) original = [3, 1, 4] new_list = sorted(original) print(original) # [3, 1, 4] (unchanged!) print(new_list) # [1, 3, 4] # Sort by key words = ['banana', 'apple', 'Cherry'] words.sort(key=str.lower) # Case-insensitive: ['apple', 'banana', 'Cherry'] students = [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 22}] students.sort(key=lambda s: s['age']) # Sort by age

List Comprehension

python
# Syntax: [expression for item in iterable if condition] squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] # Nested comprehension (flattening) matrix = [[1, 2], [3, 4], [5, 6]] flat = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6] # With transformation words = ['hello', 'world'] upper = [w.upper() for w in words] # ['HELLO', 'WORLD'] # Dict comprehension from list nums = [1, 2, 3, 4] squared_dict = {n: n**2 for n in nums} # {1: 1, 2: 4, 3: 9, 4: 16}
Key Rules
  • •Lists are MUTABLE — they can be changed in place, unlike strings and tuples
  • •append() adds ONE element (even if it's a list), extend() unpacks and adds multiple elements
  • •pop() removes and returns an element; remove() searches by value and removes first match
  • •sort() modifies in-place and returns None; sorted() returns a new list and leaves original unchanged
  • •Slicing (list[:]) creates a SHALLOW COPY — nested lists inside are still referenced
  • •List comprehensions are faster and more Pythonic than equivalent for-loop + append patterns
Your Task

Create three list utility functions: 1) `flatten(nested_list)` — flatten a 2D list using comprehension. 2) `remove_duplicates(lst)` — remove duplicates while preserving order. 3) `transpose(matrix)` — transpose a 2D matrix (rows become columns). Test with sample 2D data.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define flatten function
Should use nested list comprehension for flatten
Should define remove_duplicates function
Should use a set for O(1) duplicate lookup
Should define transpose function
Should use zip(*matrix) for transpose