Whether you are just starting your Python journey or brushing up on your core data structures, Python lists are something you will use every single day. They are versatile, powerful, and packed with built-in features.
In this quick guide, we will cover everything from the absolute basics to some advanced tricks that will make your code cleaner and faster. Letβs dive in! π
1. What is a Python List?
In Python, a list is a built-in, mutable (changeable), and ordered collection of items.
Unlike arrays in some other languages, Python lists can hold a mixture of different data types at the same timeβintegers, strings, floats, and even other lists!
# A simple list of strings
fruits = ["apple", "banana", "cherry"]
# A list with mixed data types
mixed_bag = [42, "Python", True, 3.14]
2. Navigating Lists: Indexing & Slicing πΊοΈ
Python uses zero-based indexing, meaning the first item is always at index 0. You can also use negative indexing to look at items starting from the back of the list.
Slicing Syntax: list[start:stop:step]
Slicing lets you extract a specific chunk of your list. Keep in mind that the stop index is exclusive (not included in the result).
numbers = [10, 20, 30, 40, 50]
print(numbers[0]) # Output: 10
print(numbers[-1]) # Output: 50 (the last item)
# Get items from index 1 up to (but not including) 4
print(numbers[1:4]) # Output: [20, 30, 40]
# Reverse a list using slicing step trick
print(numbers[::-1]) # Output: [50, 40, 30, 20, 10]
3. Essential List Methods Cheat Sheet π οΈ
Because lists are mutable, you can add, remove, and modify items on the fly. Here are the heavy hitters you need to memorize:
-
append(x): Adds an item to the end of the list. -
insert(i, x): Inserts an itemxat a specific indexi. -
extend(iterable): Appends all items from another list/iterable. -
remove(x): Removes the first occurrence of valuex. -
pop(i): Removes and returns the item at indexi(defaults to the last item ifiis left blank).
tech_stack = ["Python", "JavaScript"]
tech_stack.append("Rust") # ['Python', 'JavaScript', 'Rust']
tech_stack.insert(1, "HTML") # ['Python', 'HTML', 'JavaScript', 'Rust']
tech_stack.pop() # Removes 'Rust'
4. Next-Level Trick: List Comprehensions β‘
If you want to write Pythonic code, you have to learn list comprehensions. They give you a short, elegant way to create new lists based on existing ones.
Instead of writing a bulky for loop like this:
squares = []
for x in range(1, 6):
squares.append(x**2)
# Result: [1, 4, 9, 16, 25]
You can do it all in a single line:
squares = [x**2 for x in range(1, 6)]
# Result: [1, 4, 9, 16, 25]
Wrap Up π
Python lists are incredibly dynamic. Master these fundamentals, play around with list comprehensions, and you will find handling data in Python becomes a breeze.
What is your favourite Python list trick? Do you prefer slicing or built-in methods? Let me know in the comments below! π
Top comments (0)