Python Programming Lists
20+ Methods Comprehension

Python Lists Complete Guide

Learn all Python list operations - creation, manipulation, built-in methods, slicing, list comprehension with practical examples and complete reference.

Mutable

Can be modified

Ordered

Maintains order

Comprehension

Elegant creation

Slicing

Sub-list extraction

What are Python Lists?

Lists in Python are ordered, mutable collections of items. They can contain elements of different data types and are one of the most versatile data structures in Python.

Key Concept

Python lists are mutable - they can be modified after creation. Lists support indexing (list[0]), slicing (list[1:5]), and various built-in methods for manipulation.

Basic List Creation and Operations
# Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]

# Using list() constructor
list_from_string = list("hello")  # ['h', 'e', 'l', 'l', 'o']
list_from_range = list(range(5))  # [0, 1, 2, 3, 4]

# List operations
list1 = [1, 2, 3]
list2 = [4, 5, 6]

concatenation = list1 + list2      # [1, 2, 3, 4, 5, 6]
repetition = list1 * 3             # [1, 2, 3, 1, 2, 3, 1, 2, 3]
length = len(list1)                # 3

# List indexing
fruits = ["apple", "banana", "cherry", "date"]
first = fruits[0]      # "apple"
last = fruits[-1]      # "date"
second = fruits[1]     # "banana"

# List slicing
first_two = fruits[:2]     # ["apple", "banana"]
last_two = fruits[-2:]     # ["cherry", "date"]
middle = fruits[1:3]       # ["banana", "cherry"]
every_other = fruits[::2]  # ["apple", "cherry"]
reversed_list = fruits[::-1] # ["date", "cherry", "banana", "apple"]

# Modifying lists (lists are mutable!)
fruits[0] = "avocado"      # Replace first element
print(fruits)              # ["avocado", "banana", "cherry", "date"]

Python List Methods Complete Reference

Python provides powerful built-in list methods for various operations. Here's a comprehensive table of all list methods with examples.

Complete List Methods Reference Table

Category Method Description Syntax Example Result
Adding Elements append() Adds element to end of list list.append(4) [1,2,3,4]
Adding Elements extend() Adds all elements of iterable to end list.extend([4,5]) [1,2,3,4,5]
Adding Elements insert() Inserts element at specified index list.insert(1, 99) [1,99,2,3]
Removing Elements remove() Removes first occurrence of value list.remove(2) [1,3] (removes 2)
Removing Elements pop() Removes and returns element at index (default last) list.pop(1) 2 (returns removed element)
Removing Elements clear() Removes all elements from list list.clear() []
Searching index() Returns index of first occurrence list.index(3) 2 (index of 3)
Searching count() Counts occurrences of value list.count(2) 1 (count of 2)
Sorting sort() Sorts list in-place list.sort() [1,2,3,4]
Sorting reverse() Reverses list in-place list.reverse() [3,2,1]
Utility copy() Returns shallow copy of list list.copy() new list copy
Important Distinctions:
  • append() vs extend(): append adds single element, extend adds multiple
  • pop() returns removed element, remove() doesn't return anything
  • sort() modifies list in-place, sorted() returns new sorted list
  • reverse() modifies in-place, reversed() returns iterator
  • copy() creates shallow copy, use copy.deepcopy() for nested lists

List Operations & Slicing

Learn advanced list operations including slicing, concatenation, repetition, and membership testing.

List Operations Examples
# List concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(f"Concatenation: {result}")  # [1, 2, 3, 4, 5, 6]

# List repetition
print(f"Repetition: {[1, 2] * 3}")   # [1, 2, 1, 2, 1, 2]

# List length
numbers = [10, 20, 30, 40, 50]
print(f"Length of list: {len(numbers)}")  # 5

# List membership testing
print(f"20 in list: {20 in numbers}")     # True
print(f"99 in list: {99 in numbers}")     # False
print(f"20 not in list: {20 not in numbers}")  # False

# List comparison
print(f"[1,2] == [1,2]: {[1,2] == [1,2]}")  # True
print(f"[1,2] == [2,1]: {[1,2] == [2,1]}")  # False
print(f"[1,2] != [3,4]: {[1,2] != [3,4]}")  # True

# Advanced slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Basic slicing
print(f"numbers[2:6]: {numbers[2:6]}")      # [2, 3, 4, 5]
print(f"numbers[:5]: {numbers[:5]}")        # [0, 1, 2, 3, 4]
print(f"numbers[5:]: {numbers[5:]}")        # [5, 6, 7, 8, 9]
print(f"numbers[-3:]: {numbers[-3:]}")      # [7, 8, 9] (last 3)

# Step slicing
print(f"numbers[::2]: {numbers[::2]}")      # [0, 2, 4, 6, 8] (every 2nd)
print(f"numbers[1::2]: {numbers[1::2]}")    # [1, 3, 5, 7, 9] (every 2nd from index 1)

# Reverse list
print(f"numbers[::-1]: {numbers[::-1]}")    # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# Negative indexing
print(f"numbers[-1]: {numbers[-1]}")        # 9 (last element)
print(f"numbers[-2]: {numbers[-2]}")        # 8 (second last)

# Slicing with negative step
print(f"numbers[8:2:-2]: {numbers[8:2:-2]}")  # [8, 6, 4] (reverse with step 2)

# Modifying slices
numbers[2:5] = [20, 30, 40]  # Replace slice
print(f"After slice replacement: {numbers}")  # [0, 1, 20, 30, 40, 5, 6, 7, 8, 9]

numbers[1:4] = []  # Remove slice by assigning empty list
print(f"After removing slice: {numbers}")  # [0, 40, 5, 6, 7, 8, 9]

# Common list patterns
# Check if list is empty
my_list = []
if not my_list:
    print("List is empty")
    
# Get last element safely
if my_list:
    last_item = my_list[-1]
    print(f"Last item: {last_item}")
else:
    print("List is empty, no last item")

List Methods Practical Examples

See list methods in action with practical examples and real-world use cases.

List Methods Examples
# Adding elements
fruits = ["apple", "banana"]

# append() - add single element
fruits.append("cherry")
print(f"After append: {fruits}")  # ['apple', 'banana', 'cherry']

# extend() - add multiple elements
fruits.extend(["date", "elderberry"])
print(f"After extend: {fruits}")  # ['apple', 'banana', 'cherry', 'date', 'elderberry']

# insert() - insert at specific position
fruits.insert(1, "avocado")
print(f"After insert: {fruits}")  # ['apple', 'avocado', 'banana', 'cherry', 'date', 'elderberry']

# Removing elements
# remove() - remove by value
fruits.remove("banana")
print(f"After remove: {fruits}")  # ['apple', 'avocado', 'cherry', 'date', 'elderberry']

# pop() - remove by index (returns removed element)
removed = fruits.pop(2)
print(f"After pop(2): {fruits}, removed: {removed}")  # ['apple', 'avocado', 'date', 'elderberry'], removed: 'cherry'

# pop() without index - removes last element
last = fruits.pop()
print(f"After pop(): {fruits}, last: {last}")  # ['apple', 'avocado', 'date'], last: 'elderberry'

# clear() - remove all elements
fruits_copy = fruits.copy()
fruits_copy.clear()
print(f"After clear: {fruits_copy}")  # []

# Searching methods
numbers = [10, 20, 30, 20, 40, 20]

# index() - find position of element
position = numbers.index(30)
print(f"Index of 30: {position}")  # 2

# index() with start and end
position = numbers.index(20, 2)  # start searching from index 2
print(f"Index of 20 starting from index 2: {position}")  # 3

# count() - count occurrences
count_20 = numbers.count(20)
print(f"Count of 20: {count_20}")  # 3

# Sorting methods
nums = [5, 2, 8, 1, 9, 3]

# sort() - in-place sorting (ascending by default)
nums.sort()
print(f"After sort(): {nums}")  # [1, 2, 3, 5, 8, 9]

# sort() with reverse=True
nums.sort(reverse=True)
print(f"After sort(reverse=True): {nums}")  # [9, 8, 5, 3, 2, 1]

# sort() with custom key
words = ["banana", "apple", "cherry", "date"]
words.sort(key=len)  # sort by length
print(f"Sorted by length: {words}")  # ['date', 'apple', 'banana', 'cherry']

# reverse() - reverse list in-place
nums.reverse()
print(f"After reverse(): {nums}")  # [1, 2, 3, 5, 8, 9] (re-reversed)

# copy() - create shallow copy
original = [1, 2, [3, 4]]
copied = original.copy()
original[0] = 99
original[2][0] = 88
print(f"Original: {original}")  # [99, 2, [88, 4]]
print(f"Copied: {copied}")      # [1, 2, [88, 4]] (nested list is shared!)

# Built-in functions with lists
numbers = [4, 2, 9, 1, 5]

# sorted() - returns new sorted list (doesn't modify original)
sorted_nums = sorted(numbers)
print(f"Original: {numbers}")       # [4, 2, 9, 1, 5]
print(f"Sorted: {sorted_nums}")     # [1, 2, 4, 5, 9]

# reversed() - returns iterator (use list() to convert)
reversed_nums = list(reversed(numbers))
print(f"Reversed: {reversed_nums}") # [5, 1, 9, 2, 4]

# min(), max(), sum()
print(f"Min: {min(numbers)}")       # 1
print(f"Max: {max(numbers)}")       # 9
print(f"Sum: {sum(numbers)}")       # 21

List Comprehension

List comprehension provides a concise way to create lists. It's more readable and often faster than using loops.

List Comprehension Examples
# Basic list comprehension
# Traditional way
squares = []
for x in range(10):
    squares.append(x**2)
print(f"Traditional: {squares}")

# List comprehension way
squares = [x**2 for x in range(10)]
print(f"Comprehension: {squares}")  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(f"Even squares: {even_squares}")  # [0, 4, 16, 36, 64]

# Multiple conditions
numbers = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]
print(f"Divisible by 2 and 3: {numbers}")  # [0, 6, 12, 18]

# If-else in comprehension
results = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(f"Even/Odd: {results}")  # ['Even', 'Odd', 'Even', 'Odd', 'Even']

# Nested loops
pairs = [(x, y) for x in range(3) for y in range(3)]
print(f"Pairs: {pairs}")  # [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

# Flatten 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(f"Flattened matrix: {flattened}")  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Nested list comprehension (transpose matrix)
transposed = [[row[i] for row in matrix] for i in range(3)]
print(f"Transposed matrix: {transposed}")  # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

# Practical examples
# Convert strings to uppercase
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(f"Uppercase: {upper_words}")  # ['HELLO', 'WORLD', 'PYTHON']

# Extract numbers from mixed list
mixed = [1, "hello", 2.5, "world", 3, True]
numbers_only = [x for x in mixed if isinstance(x, (int, float))]
print(f"Numbers only: {numbers_only}")  # [1, 2.5, 3]

# Create list of tuples with index
fruits = ["apple", "banana", "cherry"]
indexed_fruits = [(i, fruit) for i, fruit in enumerate(fruits)]
print(f"Indexed fruits: {indexed_fruits}")  # [(0, 'apple'), (1, 'banana'), (2, 'cherry')]

# Dictionary to list of tuples using comprehension
person = {"name": "Alice", "age": 30, "city": "NYC"}
items = [(key, value) for key, value in person.items()]
print(f"Dictionary items: {items}")  # [('name', 'Alice'), ('age', 30), ('city', 'NYC')]

# Set comprehension (similar syntax)
unique_lengths = {len(word) for word in words}
print(f"Unique word lengths: {unique_lengths}")  # {5, 6}

# Generator expression (uses parentheses, not brackets)
gen = (x**2 for x in range(5))
print(f"Generator: {list(gen)}")  # [0, 1, 4, 9, 16] (converted to list for display)

Working with Nested Lists

Nested lists (lists within lists) are common in Python for representing matrices, grids, and hierarchical data.

Nested Lists Examples
# Creating nested lists (2D list / matrix)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Accessing elements
print(f"matrix[0][0]: {matrix[0][0]}")  # 1
print(f"matrix[1][2]: {matrix[1][2]}")  # 6
print(f"matrix[2][1]: {matrix[2][1]}")  # 8

# Iterating through nested lists
print("\nMatrix elements:")
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()  # new line after each row

# Using enumerate for indices
print("\nMatrix with indices:")
for i, row in enumerate(matrix):
    for j, element in enumerate(row):
        print(f"matrix[{i}][{j}] = {element}")

# Modifying nested lists
matrix[1][1] = 99
print(f"\nModified matrix: {matrix}")  # [[1, 2, 3], [4, 99, 6], [7, 8, 9]]

# Adding rows
matrix.append([10, 11, 12])
print(f"After adding row: {matrix}")  # [[1, 2, 3], [4, 99, 6], [7, 8, 9], [10, 11, 12]]

# Adding columns
for row in matrix:
    row.append(0)
print(f"After adding column: {matrix}")  # Each row now has 4 elements

# Transpose matrix (swap rows and columns)
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(f"\nTransposed matrix: {transposed}")

# Flatten nested list
flattened = [element for row in matrix for element in row]
print(f"Flattened matrix: {flattened}")

# Deep vs shallow copy for nested lists
import copy

original = [[1, 2], [3, 4]]

# Shallow copy (nested lists are shared)
shallow_copy = original.copy()
original[0][0] = 99
print(f"\nOriginal: {original}")        # [[99, 2], [3, 4]]
print(f"Shallow copy: {shallow_copy}")  # [[99, 2], [3, 4]] (also changed!)

# Deep copy (completely independent)
original = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original)
original[0][0] = 99
print(f"\nOriginal: {original}")        # [[99, 2], [3, 4]]
print(f"Deep copy: {deep_copy}")        # [[1, 2], [3, 4]] (unchanged)

# Practical example: Student grades
grades = [
    ["Alice", [85, 90, 78]],
    ["Bob", [92, 88, 94]],
    ["Charlie", [76, 85, 80]]
]

# Calculate average for each student
print("\nStudent averages:")
for student, scores in grades:
    average = sum(scores) / len(scores)
    print(f"{student}: {average:.2f}")

# Find student with highest average
highest = max(grades, key=lambda x: sum(x[1])/len(x[1]))
print(f"\nHighest average: {highest[0]} with {sum(highest[1])/len(highest[1]):.2f}")

# 3D list example (cube)
cube = [
    [[1, 2], [3, 4]],
    [[5, 6], [7, 8]]
]

print(f"\n3D list (cube) access: cube[0][1][0] = {cube[0][1][0]}")  # 3

List Practice Exercises

Try these exercises to test your understanding of Python lists.

List Practice Script
# Python Lists Practice Exercises

print("=== Exercise 1: Basic List Operations ===")
# 1. Create a list of 5 numbers and find their sum
numbers = [10, 20, 30, 40, 50]
total = sum(numbers)
print(f"Numbers: {numbers}, Sum: {total}")

# 2. Create a list of strings and find the longest string
words = ["apple", "banana", "cherry", "date", "elderberry"]
longest = max(words, key=len)
print(f"Words: {words}, Longest: '{longest}' ({len(longest)} chars)")

print("\n=== Exercise 2: List Manipulation ===")
# 3. Remove duplicates from a list while preserving order
def remove_duplicates(lst):
    seen = set()
    result = []
    for item in lst:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

numbers = [1, 2, 2, 3, 4, 4, 5, 1, 2]
unique = remove_duplicates(numbers)
print(f"Original: {numbers}")
print(f"Without duplicates: {unique}")

# 4. Rotate list by k positions
def rotate_list(lst, k):
    k = k % len(lst)  # Handle k larger than list length
    return lst[-k:] + lst[:-k]

numbers = [1, 2, 3, 4, 5, 6, 7]
rotated = rotate_list(numbers, 3)
print(f"Original: {numbers}")
print(f"Rotated by 3: {rotated}")

print("\n=== Exercise 3: List Comprehension ===")
# 5. Create list of squares for even numbers only
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(f"Even squares (1-10): {even_squares}")

# 6. Flatten a nested list
nested = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened = [num for sublist in nested for num in sublist]
print(f"Nested: {nested}")
print(f"Flattened: {flattened}")

print("\n=== Exercise 4: List Methods ===")
# 7. Implement stack using list methods
stack = []
stack.append(1)  # push
stack.append(2)
stack.append(3)
print(f"Stack after pushes: {stack}")
popped = stack.pop()  # pop
print(f"Popped: {popped}, Stack after pop: {stack}")

# 8. Implement queue using list methods (inefficient but for practice)
queue = []
queue.append(1)  # enqueue
queue.append(2)
queue.append(3)
dequeued = queue.pop(0)  # dequeue (pop from front)
print(f"Dequeued: {dequeued}, Queue after dequeue: {queue}")

print("\n=== Exercise 5: Advanced Operations ===")
# 9. Find second largest number in list
def second_largest(lst):
    unique = sorted(set(lst), reverse=True)
    return unique[1] if len(unique) > 1 else None

numbers = [10, 5, 8, 20, 15, 20, 8]
second = second_largest(numbers)
print(f"Numbers: {numbers}")
print(f"Second largest: {second}")

# 10. Merge and sort two lists
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
merged = sorted(list1 + list2)
print(f"List 1: {list1}")
print(f"List 2: {list2}")
print(f"Merged and sorted: {merged}")

# 11. Find common elements between two lists
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
common = [x for x in list_a if x in list_b]
print(f"\nList A: {list_a}")
print(f"List B: {list_b}")
print(f"Common elements: {common}")

# 12. Split list into chunks
def chunk_list(lst, size):
    return [lst[i:i+size] for i in range(0, len(lst), size)]

numbers = list(range(1, 11))
chunks = chunk_list(numbers, 3)
print(f"\nNumbers: {numbers}")
print(f"Chunks of 3: {chunks}")

# 13. Find all pairs that sum to target
def find_pairs(lst, target):
    pairs = []
    for i in range(len(lst)):
        for j in range(i+1, len(lst)):
            if lst[i] + lst[j] == target:
                pairs.append((lst[i], lst[j]))
    return pairs

numbers = [1, 2, 3, 4, 5, 6]
target = 7
pairs = find_pairs(numbers, target)
print(f"\nNumbers: {numbers}")
print(f"Pairs that sum to {target}: {pairs}")

Key Takeaways

  • Python lists are mutable, ordered collections that can contain any data type
  • Lists are created with square brackets: [] or using list() constructor
  • Indexing: list[0] gets first element, list[-1] gets last
  • Slicing: list[start:end:step] extracts sub-lists
  • Key methods: append(), extend(), insert(), remove(), pop(), sort(), reverse(), copy()
  • List comprehension provides concise way to create lists: [x**2 for x in range(10)]
  • Use in operator for membership testing: 5 in [1,2,3,4,5]
  • Built-in functions: len(), sum(), min(), max(), sorted(), reversed()
  • Lists can be nested: [[1,2], [3,4]] creates 2D list
  • copy() creates shallow copy; use copy.deepcopy() for nested lists
  • Lists support concatenation (+) and repetition (*) operators