The Ultimate List Guide

Learn and master the essential techniques for manipulating, accessing, and working with Python lists efficiently.

Python Lists
Store multiple items in a single variable with order and flexibility
my_list = [item1, item2, item3]
Core Concept

Python Lists

Lists are used to store multiple items in a single variable. They are one of Python’s four built-in collection data types, along with Tuple, Set, and Dictionary, each with different characteristics and use cases.

Core Concept

Creating a List

Lists are created using square brackets []. Each item is separated by a comma.

vehicles = ["car", "bike", "truck"]
print(vehicles)
# Output: ['car', 'bike', 'truck']

List Order and Indexing

List items are ordered, meaning that the order of items is preserved. Each item has an index starting at 0:

vehicles = ["car", "bike", "truck"]
print(vehicles[0])  # car (first item)
print(vehicles[1])  # bike (second item)
print(vehicles[2])  # truck (third item)

Negative indexing allows access from the end of the list:

print(vehicles[-1])  # truck (last item)
print(vehicles[-2])  # bike (second last item)

Changeable Lists

Lists are changeable (mutable). You can modify items, add new items, or remove items after the list has been created.

vehicles[1] = "scooter"  # Change "bike" to "scooter"
vehicles.append("bus")       # Add a new item at the end
print(vehicles)
# Output: ['car', 'scooter', 'truck', 'bus']

Duplicates

Lists allow duplicate items because they are indexed. Multiple items can have the same value:

vehicles = ["car", "bike", "car", "truck"]
print(vehicles)
# Output: ['car', 'bike', 'car', 'truck']

List Length

Use len() to determine the number of items in a list:

vehicles = ["car", "bike", "truck"]
print(len(vehicles))
# Output: 3

List Item Data Types

A list can contain items of different data types, including numbers, strings, booleans, or even other lists:

mixed_list = ["car", 42, True, 3.14]
print(mixed_list)
# Output: ['car', 42, True, 3.14]

List Type

vehicles = ["car", "bike", "truck"]
print(type(vehicles))
# Output: <class 'list'>

Using the list() Constructor

Lists can also be created using the list() constructor from another iterable, such as a tuple:

numbers_tuple = (1, 2, 3)
numbers_list = list(numbers_tuple)
print(numbers_list)
# Output: [1, 2, 3]
Accessing List Items
Learn how to retrieve and modify items in a list using indexes, slices, and nested structures
my_list[index] or my_list[start:stop:step]
Core Concept

Accessing List Items

Python lists are ordered and indexed collections that can store elements of any data type, including numbers, strings, floats, and even other lists (nested lists). This section explains all the ways to access and manipulate list items.

Core Concept

Access by Index

Each item in a list has an index starting from 0. You can access an element by specifying its index inside square brackets []:

my_list = [0.5, 0, 4, "6", "Hello"]

# Print the entire list
print(f"My list: {my_list}")
# Output: [0.5, 0, 4, '6', 'Hello']

# Accessing the 3rd element (index 2)
a = my_list[2]
print(f"Element at index 2: {a}")
# Output: 4

Indexing allows retrieval of a single element. If you provide an index that is out of bounds, Python raises an IndexError.

Negative Indexing

Negative indexing starts from the end of the list: -1 is the last element, -2 is the second last, and so on:

my_list[-1] = "bye"  # Change last element
print(f"Modified list: {my_list}")
# Output: [0.5, 0, 4, '6', 'bye']

print(my_list[-2])
# Output: '6' (second last element)

Accessing Nested Lists

Lists can contain other lists. To access items in nested lists, chain the indices:

my_list = [45, [3, 4, 6], "word", 34.6, ["a", "b", "c"]]

# Access the second element, which is a list
nested_list = my_list[1]
print(f"Nested list at index 1: {nested_list}")
# Output: [3, 4, 6]

# Access 'c' from the last nested list
nested_element = my_list[4][2]
print(f"Element at my_list[4][2]: {nested_element}")
# Output: c

Slicing Lists

Slicing allows you to access a subset of elements using the syntax: list[start:stop:step]. The slice returns a new list from start index up to but not including stop. The step specifies the interval.

numbers = [10, 20, 30, 40, 50, 60, 70, 80]

# Slice from index 1 to 3 (1,2,3-1)
print(f"numbers[1:4] -> {numbers[1:4]}")
# Output: [20, 30, 40]

# Slice from start to index 2
print(f"numbers[:3] -> {numbers[:3]}")
# Output: [10, 20, 30]

# Slice from index 3 to the end
print(f"numbers[3:] -> {numbers[3:]}")
# Output: [40, 50, 60, 70, 80]

# Slice with step 2 (every 2nd element)
print(numbers[0:7:2])
# Output: [10, 30, 50, 70]

# Slice with step 3 starting at index 1
print(numbers[1::3])
# Output: [20, 50, 80]

# Negative slicing
print(numbers[-5:-2])
# Output: [40, 50, 60]

# Up to third last element
print(numbers[:-3])
# Output: [10, 20, 30, 40, 50]

# Reverse the list
print(numbers[::-1])
# Output: [80, 70, 60, 50, 40, 30, 20, 10]

# Slice backwards from index 5 to 2
print(numbers[5:1:-1])
# Output: [60, 50, 40, 30]

Slicing is powerful for creating sublists, reversing lists, or skipping elements in regular patterns.

Checking if an Item Exists

You can check if an element exists in a list using the in keyword:

my_list = [0.5, 0, 4, "6", "Hello"]

if "6" in my_list:
    print("Item found!")
# Output: Item found!
Changing List Items
Learn how to modify, add, and remove items in a list, including nested lists
my_list[index] = value, list.append(value), list.remove(value)
Core Concept

Changing List Items

Lists in Python are mutable, meaning you can change items, add new items, remove items, and modify nested lists. This card explains all these operations with clear examples.

Core Concept

Modifying an Item by Index

You can change a specific item by assigning a new value to its index:

my_list = [0.5, 0, 4, "6", "Hello"]

# Change the 3rd element (index 2)
my_list[2] = 99
print(f"Modified list: {my_list}")
# Output: [0.5, 0, 99, '6', 'Hello']

# Change the last element using negative indexing
my_list[-1] = "bye"
print(f"Modified list: {my_list}")
# Output: [0.5, 0, 99, '6', 'bye']

Adding Items

There are multiple ways to add new items to a list:

vehicles = ["car", "bike", "truck"]

# Append an item at the end
vehicles.append("bus")
print(vehicles)
# Output: ['car', 'bike', 'truck', 'bus']

# Insert an item at a specific index
vehicles.insert(1, "scooter")
print(vehicles)
# Output: ['car', 'scooter', 'bike', 'truck', 'bus']

# Extend a list with multiple items from another list
vehicles.extend(["skateboard", "rollerblades"])
print(vehicles)
# Output: ['car', 'scooter', 'bike', 'truck', 'bus', 'skateboard', 'rollerblades']

Removing Items

You can remove items by value, index, or clear the entire list:

vehicles = ['car', 'scooter', 'bike', 'truck', 'bus']

# Remove by value
vehicles.remove("bike")
print(vehicles)
# Output: ['car', 'scooter', 'truck', 'bus']

# Remove by index using pop (removes and returns the item)
last_vehicle = vehicles.pop()
print(f"Removed: {last_vehicle}")
print(vehicles)
# Output: Removed: bus
# ['car', 'scooter', 'truck']

# Remove a specific index
vehicles.pop(1)
print(vehicles)
# Output: ['car', 'truck']

# Clear the entire list
vehicles.clear()
print(vehicles)
# Output: []

Modifying Multiple Items with Slices

You can change multiple consecutive items using slicing:

numbers = [10, 20, 30, 40, 50]

# Replace a slice with new values
numbers[1:4] = [21, 31, 41]
print(numbers)
# Output: [10, 21, 31, 41, 50]

# Replace multiple elements with fewer or more elements
numbers[0:2] = [1, 2, 3]
print(numbers)
# Output: [1, 2, 3, 31, 41, 50]

Modifying Nested Lists

Nested lists can be modified by chaining indices:

my_list = [1, [10, 20, 30], 3]

# Change 20 to 25 in nested list
my_list[1][1] = 25
print(my_list)
# Output: [1, [10, 25, 30], 3]

# Add new element to nested list
my_list[1].append(35)
print(my_list)
# Output: [1, [10, 25, 30, 35], 3]
Adding List Items
Learn how to add new items to a list using append, insert, extend, and nested lists
list.append(value), list.insert(index, value), list.extend(iterable)
Core Concept

Adding List Items

Since lists are mutable, you can easily add new items at the end, at a specific position, or by extending with multiple items. This card explains all these methods with examples.

Core Concept

Append an Item

The append() method adds a single element to the end of the list:

fruits = ["apple", "banana"]
fruits.append("cherry")  # Add at the end
print(fruits)
# Output: ['apple', 'banana', 'cherry']

Insert an Item at a Specific Index

Use insert(index, value) to add an item at a specific position. The rest of the items are shifted to the right:

vehicles = ["car", "bike", "truck"]
vehicles.insert(1, "scooter")  # Insert at index 1
print(vehicles)
# Output: ['car', 'scooter', 'bike', 'truck']

Extend List with Another Iterable

extend() adds multiple elements from another list (or any iterable) to the end of the list:

numbers = [1, 2, 3]
more_numbers = [4, 5, 6]

numbers.extend(more_numbers)
print(numbers)
# Output: [1, 2, 3, 4, 5, 6]

Adding Items to Nested Lists

Nested lists can also be extended or modified using standard methods:

nested_list = [1, [10, 20], 3]

# Append to nested list
nested_list[1].append(30)
print(nested_list)
# Output: [1, [10, 20, 30], 3]

# Insert into nested list
nested_list[1].insert(1, 15)
print(nested_list)
# Output: [1, [10, 15, 20, 30], 3]
Removing List Items
Learn how to remove items from a list using remove, pop, del, clear, and in nested lists
list.remove(value), list.pop(index), del list[index], list.clear()
Core Concept

Removing List Items

Python lists are mutable, which means items can be removed in several ways: by value, by index, clearing all items, or modifying nested lists. This card explains all removal methods with examples.

Core Concept

Remove by Value

Use remove(value) to remove the first occurrence of a value. If the value is not found, Python raises a ValueError:

fruits = ["apple", "banana", "cherry", "banana"]

# Remove first occurrence of 'banana'
fruits.remove("banana")
print(fruits)
# Output: ['apple', 'cherry', 'banana']

Remove by Index with pop()

pop(index) removes the item at the given index and returns it. If no index is specified, it removes the last item:

vehicles = ["car", "scooter", "truck", "bus"]

# Remove and return last item
last_vehicle = vehicles.pop()
print(f"Removed: {last_vehicle}")
print(vehicles)
# Output: Removed: bus
# ['car', 'scooter', 'truck']

# Remove item at index 1
removed_item = vehicles.pop(1)
print(f"Removed: {removed_item}")
print(vehicles)
# Output: Removed: scooter
# ['car', 'truck']

Remove Items using del

The del statement removes an item at a specific index or an entire slice:

numbers = [10, 20, 30, 40, 50]

# Remove item at index 2
del numbers[2]
print(numbers)
# Output: [10, 20, 40, 50]

# Remove a slice
del numbers[1:3]
print(numbers)
# Output: [10, 50]

Clear the Entire List

clear() removes all items from the list, leaving it empty:

my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list)
# Output: []

Removing Items from Nested Lists

Nested lists can be modified by accessing them through their index:

nested_list = [1, [10, 20, 30], 3]

# Remove element from nested list
nested_list[1].remove(20)
print(nested_list)
# Output: [1, [10, 30], 3]

# Pop element from nested list
popped = nested_list[1].pop(0)
print(popped)
print(nested_list)
# Output: 10
# [1, [30], 3]
Looping Through Lists
Learn how to iterate through list items using for, while, and enumerate
for item in list:, while condition:, for i, item in enumerate(list):
Core Concept

Looping Through Lists

Iterating through lists allows you to process each item individually. Python provides several ways to loop through lists including for loops, while loops, and the enumerate() function.

Core Concept

Looping with for

The for loop is the most common way to iterate through each item in a list:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
# Output:
# apple
# banana
# cherry

Modifying Items in a Loop

To modify items while looping, you need to access them by index:

numbers = [1, 2, 3, 4, 5]

# Multiply each number by 10
for i in range(len(numbers)):
    numbers[i] = numbers[i] * 10

print(numbers)
# Output: [10, 20, 30, 40, 50]

Looping with while

The while loop iterates as long as a condition is true:

numbers = [10, 20, 30]
i = 0

while i < len(numbers):
    print(numbers[i])
    i += 1
# Output:
# 10
# 20
# 30

Looping with enumerate()

enumerate() provides both the index and the value while looping:

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry

Looping Through Nested Lists

Nested lists can be looped using nested loops:

nested_list = [[1, 2], [3, 4], [5, 6]]

for sublist in nested_list:
    for item in sublist:
        print(item)
# Output:
# 1
# 2
# 3
# 4
# 5
# 6
List Comprehensions
Create new lists concisely using expressions and loops
[expression for item in iterable if condition]
Advanced Concept

List Comprehensions

List comprehensions provide a concise and readable way to create new lists by applying expressions to each item in an iterable, optionally including conditions.

Advanced Concept

Basic List Comprehension

The basic syntax creates a new list by applying an expression to each item in an existing iterable:

numbers = [1, 2, 3, 4, 5]

# Square each number
squares = [n**2 for n in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25]

List Comprehension with Condition

You can include a condition to filter items:

numbers = [1, 2, 3, 4, 5, 6]

# Only even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6]

Applying Functions in List Comprehensions

You can use functions or complex expressions for each item:

words = ["hello", "world", "python"]

# Convert each word to uppercase
upper_words = [word.upper() for word in words]
print(upper_words)
# Output: ['HELLO', 'WORLD', 'PYTHON']

Nested Loops in List Comprehensions

You can include multiple loops to flatten nested lists or combine elements:

matrix = [[1, 2], [3, 4], [5, 6]]

# Flatten matrix
flat = [num for row in matrix for num in row]
print(flat)
# Output: [1, 2, 3, 4, 5, 6]

Using Conditional Expressions

You can apply different expressions based on conditions inside a comprehension:

numbers = [1, 2, 3, 4, 5]

# Replace even numbers with 'even', odd numbers remain
labels = ['even' if n % 2 == 0 else n for n in numbers]
print(labels)
# Output: [1, 'even', 3, 'even', 5]

List Comprehension vs Standard Loop

List comprehensions are more concise and readable than traditional loops:

# Traditional loop
squares = []
for n in range(5):
    squares.append(n**2)
print(squares)
# Output: [0, 1, 4, 9, 16]

# List comprehension
squares2 = [n**2 for n in range(5)]
print(squares2)
# Output: [0, 1, 4, 9, 16]
Sorting Lists
Learn how to sort lists using sort() and sorted() with custom keys and order
list.sort(), sorted(list), list.sort(reverse=True)
Core Concept

Sorting Lists

Python provides multiple ways to sort lists. You can sort in-place using sort() or create a sorted copy using sorted(). Sorting can be ascending or descending, and you can use custom key functions.

Core Concept

Using sort()

sort() sorts the list in-place (modifies the original list) in ascending order by default:

numbers = [5, 2, 9, 1, 7]
numbers.sort()
print(numbers)
# Output: [1, 2, 5, 7, 9]

Sorting in Descending Order

Use reverse=True to sort from largest to smallest:

numbers = [5, 2, 9, 1, 7]
numbers.sort(reverse=True)
print(numbers)
# Output: [9, 7, 5, 2, 1]

Using sorted() to Return a New List

sorted() returns a new sorted list without modifying the original:

numbers = [5, 2, 9, 1, 7]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
print(numbers)  # Original list remains unchanged
# Output:
# [1, 2, 5, 7, 9]
# [5, 2, 9, 1, 7]

Sorting Strings Alphabetically

Lists of strings can be sorted alphabetically:

fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)
# Output: ['apple', 'banana', 'cherry']

Sorting with Key Functions

You can customize the sorting order using the key parameter, such as sorting by string length:

words = ["banana", "apple", "kiwi", "cherry"]
words.sort(key=len)
print(words)
# Output: ['kiwi', 'apple', 'banana', 'cherry']

Sorting Nested Lists by Element

When sorting a list of lists, you can sort by a specific element in each sublist using a key:

matrix = [[1, 4], [2, 2], [3, 1]]
# Sort by second element of each sublist
matrix.sort(key=lambda x: x[1])
print(matrix)
# Output: [[3, 1], [2, 2], [1, 4]]
Copying Lists
Create copies of lists safely without affecting the original
new_list = old_list.copy(), new_list = old_list[:], new_list = list(old_list)
Core Concept

Copying Lists

Copying lists allows you to create a new list with the same items as the original. This is important to avoid modifying the original list when working with a copy. Python provides several ways to copy lists: using copy(), slicing, and the list() constructor.

Core Concept

Using copy() Method

The copy() method creates a shallow copy of a list:

original = [1, 2, 3, 4]
copied = original.copy()

copied.append(5)
print("Original:", original)
print("Copied:", copied)
# Output:
# Original: [1, 2, 3, 4]
# Copied: [1, 2, 3, 4, 5]

Copying with Slicing

You can create a copy by slicing the entire list [:]:

original = ["a", "b", "c"]
copied = original[:]

copied[0] = "z"
print("Original:", original)
print("Copied:", copied)
# Output:
# Original: ['a', 'b', 'c']
# Copied: ['z', 'b', 'c']

Copying with list() Constructor

The list() constructor can create a new list from an existing iterable:

original = [10, 20, 30]
copied = list(original)

copied.append(40)
print("Original:", original)
print("Copied:", copied)
# Output:
# Original: [10, 20, 30]
# Copied: [10, 20, 30, 40]

Shallow vs Deep Copy

All methods above create a shallow copy, which means nested lists inside the list are still references to the original nested lists. To create a deep copy, use the copy module:

import copy

original = [1, [2, 3], 4]
shallow = original.copy()
deep = copy.deepcopy(original)

# Modify nested list
original[1].append(99)

print("Original:", original)
print("Shallow:", shallow)
print("Deep:", deep)
# Output:
# Original: [1, [2, 3, 99], 4]
# Shallow: [1, [2, 3, 99], 4]
# Deep: [1, [2, 3], 4]
Joining Lists
Combine multiple lists into a single list using different methods
list1 + list2, list1.extend(list2), [item for sublist in lists for item in sublist]
Core Concept

Joining Lists

Joining lists allows you to combine multiple lists into a single list. Python provides several ways to do this, each with slightly different behavior.

Core Concept

Using + Operator

You can concatenate two or more lists using the + operator. This creates a new list:

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

combined = list1 + list2
print(combined)
# Output: [1, 2, 3, 4, 5, 6]

Using extend()

The extend() method adds all elements from another list to the original list (modifies the list in-place):

list1 = ["a", "b"]
list2 = ["c", "d"]

list1.extend(list2)
print(list1)
# Output: ['a', 'b', 'c', 'd']

Using List Comprehension

List comprehension can combine multiple lists and optionally apply transformations:

lists = [[1, 2], [3, 4], [5, 6]]

combined = [item for sublist in lists for item in sublist]
print(combined)
# Output: [1, 2, 3, 4, 5, 6]

Repeating Lists with *

You can repeat a list multiple times using the * operator:

nums = [1, 2]
repeated = nums * 3
print(repeated)
# Output: [1, 2, 1, 2, 1, 2]

Joining Lists of Strings

If you have a list of strings, you can join them into a single string using the join() method of strings:

words = ["Hello", "world", "!"]
sentence = " ".join(words)
print(sentence)
# Output: Hello world !