Python Lists Cheat Sheet: Quick Reference for Developers
A concise, no-fluff reference covering Python list creation, access, modification, sorting, comprehensions, copying, and common pitfalls. Perfect for developers who need a quick syntax reminder.
Advertisement
If you've been working with Python for any length of time, you already know lists are the workhorses of the language. They're flexible, fast, and everywhere. But even experienced developers sometimes need a quick refresher on the syntax or a reminder of that one method they always forget.
This cheat sheet is for you. No fluff, no long explanations—just the essentials you need to get your work done.
Creating Lists
The basics, but worth repeating:
# Empty list
my_list = []
# List with values
fruits = ["apple", "banana", "cherry"]
# Mixed types (yes, Python allows this)
mixed = [1, "hello", 3.14, True]
# Using list() constructor
numbers = list(range(5)) # [0, 1, 2, 3, 4]
Accessing Elements
Python uses zero-based indexing, which trips up beginners but becomes second nature fast.
fruits = ["apple", "banana", "cherry", "date"]
# First element
fruits[0] # "apple"
# Last element
fruits[-1] # "date"
# Slicing
fruits[1:3] # ["banana", "cherry"]
fruits[:2] # ["apple", "banana"]
fruits[2:] # ["cherry", "date"]
Modifying Lists
Lists are mutable, meaning you can change them in place. This is one of their biggest strengths.
# Change an element
fruits[1] = "blueberry"
# Add to the end
fruits.append("elderberry")
# Insert at a specific position
fruits.insert(0, "apricot")
# Remove by value
fruits.remove("banana") # removes first occurrence
# Remove by index
popped = fruits.pop(2) # removes and returns element at index 2
# Remove without returning
del fruits[0]
# Clear the entire list
fruits.clear()
Combining and Repeating
Lists play nicely together. You can join them or repeat them with simple operators.
list_a = [1, 2, 3]
list_b = [4, 5, 6]
# Concatenation
combined = list_a + list_b # [1, 2, 3, 4, 5, 6]
# Repetition
repeated = list_a * 3 # [1, 2, 3, 1, 2, 3, 1, 2, 3]
# Extend in place
list_a.extend(list_b) # list_a becomes [1, 2, 3, 4, 5, 6]
Checking Membership
Need to know if something's in your list? Python makes it clean.
fruits = ["apple", "banana", "cherry"]
"apple" in fruits # True
"grape" not in fruits # True
Finding Things
When you need the position of an element, index() is your friend. Just remember it raises a ValueError if the item isn't found.
fruits = ["apple", "banana", "cherry", "banana"]
fruits.index("banana") # 1 (first occurrence)
fruits.index("banana", 2) # 3 (start searching from index 2)
fruits.count("banana") # 2
len(fruits) # 4
Adding and Removing
These are the methods you'll use daily.
# Append (adds one element)
fruits.append("grape")
# Extend (adds multiple elements from an iterable)
fruits.extend(["kiwi", "lemon"])
# Insert at position
fruits.insert(1, "blueberry")
# Remove by value (first occurrence only)
fruits.remove("banana")
# Pop by index (defaults to last)
last = fruits.pop() # removes and returns last
first = fruits.pop(0) # removes and returns first
Sorting and Reversing
Sorting lists is straightforward, but there's a subtle difference between sorting in place and creating a new sorted list.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Sort in place (modifies original)
numbers.sort() # ascending
numbers.sort(reverse=True) # descending
# Create a new sorted list (original unchanged)
sorted_numbers = sorted(numbers)
sorted_desc = sorted(numbers, reverse=True)
# Reverse in place
numbers.reverse()
# Create a reversed copy
reversed_numbers = list(reversed(numbers))
List Comprehensions
This is where Python lists really shine. List comprehensions are more readable and faster than traditional loops for many tasks.
# Basic: squares of numbers 0-9
squares = [x**2 for x in range(10)]
# With condition: even squares only
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Nested loop: flatten a matrix
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", "python"]
upper_words = [word.upper() for word in words]
Common Operations at a Glance
Here's a quick reference for the operations you'll use most often.
| Operation | Code | Example Result |
|---|---|---|
| Length | len(list) |
4 |
| Minimum | min(list) |
1 |
| Maximum | max(list) |
9 |
| Sum | sum(list) |
22 |
| Check if empty | if not list: |
True if empty |
| Copy (shallow) | list.copy() or list[:] |
New list |
| Join to string | ", ".join(list) |
"apple, banana, cherry" |
Sorting with Custom Logic
Sometimes you need to sort by something other than the natural order. Python's key parameter is your friend here.
# Sort by string length
words = ["python", "java", "c", "javascript"]
words.sort(key=len) # ["c", "java", "python", "javascript"]
# Sort by last character
words.sort(key=lambda x: x[-1])
# Sort a list of dictionaries by a key
people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
people.sort(key=lambda person: person["age"])
Copying Lists
This one trips up a lot of developers. Assignment doesn't copy—it creates a reference.
original = [1, 2, 3]
# This does NOT create a copy
wrong = original
wrong.append(4) # original is also modified!
# Proper ways to copy
copy1 = original.copy()
copy2 = original[:]
copy3 = list(original)
# For nested lists, use deepcopy
import copy
nested = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(nested)
List Methods Cheat Sheet
Here's every method you need to know, organized by what they do.
Adding Elements
append(x)– Add one element to the endextend(iterable)– Add all elements from an iterableinsert(i, x)– Insert at position i
Removing Elements
remove(x)– Remove first occurrence of xpop(i)– Remove and return element at i (default last)clear()– Remove all elements
Finding and Counting
index(x, start, end)– Return index of first occurrencecount(x)– Count occurrences of x
Reordering
sort(key, reverse)– Sort in placereverse()– Reverse in place
Copying
copy()– Shallow copy
Real-World Example: Processing User Data
Let's say you're working on a project for PythonSkillset and need to process a list of user scores. Here's how you might handle it:
scores = [85, 92, 78, 95, 88, 72, 91]
# Filter passing scores (>= 80)
passing = [score for score in scores if score >= 80]
# Calculate average
average = sum(scores) / len(scores)
# Find top 3 scores
top_three = sorted(scores, reverse=True)[:3]
# Add a new score
scores.append(89)
# Remove the lowest score
scores.remove(min(scores))
print(f"Passing scores: {passing}")
print(f"Average: {average:.1f}")
print(f"Top 3: {top_three}")
When to Use Lists vs. Other Data Structures
Lists are great, but they're not always the right tool. Here's a quick guide:
- Use a list when you need an ordered collection that you'll modify frequently
- Use a tuple when you need an ordered collection that shouldn't change
- Use a set when you need unique elements and fast membership testing
- Use a dictionary when you need key-value pairs
Common Pitfalls to Avoid
Even seasoned developers make these mistakes. Here's what to watch for:
Modifying a list while iterating over it – This can skip elements or cause errors. Instead, iterate over a copy:
# Wrong
for item in my_list:
if condition(item):
my_list.remove(item)
# Right
for item in my_list.copy():
if condition(item):
my_list.remove(item)
Using = instead of copy() – As mentioned earlier, this creates a reference, not a new list. Always use .copy(), list(), or slicing [:] when you need an independent copy.
Forgetting that sort() returns None – This is a common gotcha. sort() modifies the list in place and returns None. If you want a new sorted list, use sorted().
Performance Tips
Lists are fast for most operations, but there are a few things to keep in mind:
- Appending is O(1) amortized – it's very fast
- Inserting at the beginning is O(n) – use
collections.dequeif you need frequent left-side inserts - Membership testing (
in) is O(n) – for large lists, consider using a set - Slicing creates a new list, which can be memory-intensive for large lists
Wrapping Up
Lists are one of those features that make Python so pleasant to work with. They're simple enough for beginners but powerful enough for complex data processing. Keep this cheat sheet handy, and you'll never have to Google "how to remove element from list Python" again.
At PythonSkillset, we believe that mastering the fundamentals—like lists—is what separates good developers from great ones. The more comfortable you are with these basics, the more you can focus on solving real problems instead of fighting with syntax.
Advertisement
Comments
Questions, corrections, and tips stay visible for everyone reading this page.
Join the discussion
No comments yet
Be the first to leave a note — it helps the next reader.