List CheatSheet

Here's a Python List cheatsheet:

Creating a List

my_list = []  # An empty list
my_list = [1, 2, 3]  # A list with three integers
my_list = ["apple", "banana", "cherry"]  # A list with three strings

Accessing Elements in a List

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

# Access the first element
print(my_list[0])  # Output: "apple"

# Access the last element
print(my_list[-1])  # Output: "cherry"

Slicing a List

my_list = ["apple", "banana", "cherry", "date"]

# Slice from index 1 to index 3 (exclusive)
print(my_list[1:3])  # Output: ["banana", "cherry"]

# Slice from the beginning to index 2 (exclusive)
print(my_list[:2])  # Output: ["apple", "banana"]

# Slice from index 2 to the end
print(my_list[2:])  # Output: ["cherry", "date"]

Modifying a List

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

# Append an element to the end
my_list.append("date")

# Insert an element at a specific index
my_list.insert(1, "blueberry")

# Remove an element by value
my_list.remove("banana")

# Remove an element by index
del my_list[0]

# Replace an element by index
my_list[1] = "cherry"

List Comprehension

# Create a new list with the squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]

# Create a new list with the even numbers from 0 to 9
evens = [x for x in range(10) if x % 2 == 0]

Other Useful List Operations

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

# Get the length of the list
print(len(my_list))  # Output: 3

# Check if an element is in the list
print("banana" in my_list)  # Output: True

# Reverse the order of the list
my_list.reverse()

# Sort the list in ascending order
my_list.sort()

# Copy a list
new_list = my_list.copy()

Concatenating Lists

my_list1 = ["apple", "banana"]
my_list2 = ["cherry", "date"]
my_list3 = my_list1 + my_list2

print(my_list3)  # Output: ["apple", "banana", "cherry", "date"]

Removing Duplicates

my_list = ["apple", "banana", "cherry", "banana", "date", "apple"]
unique_list = list(set(my_list))

print(unique_list)  # Output: ["apple", "banana", "cherry", "date"]

Counting Occurrences

my_list = ["apple", "banana", "cherry", "banana", "date", "apple"]
banana_count = my_list.count("banana")

print(banana_count)  # Output: 2

Extending a List

my_list1 = ["apple", "banana"]
my_list2 = ["cherry", "date"]
my_list1.extend(my_list2)

print(my_list1)  # Output: ["apple", "banana", "cherry", "date"]

Clearing a List

my_list = ["apple", "banana", "cherry"]
my_list.clear()

print(my_list)  # Output: []

List as Stack

stack = ["apple", "banana", "cherry"]
stack.append("date")
top = stack.pop()

print(top)  # Output: "date"

Last updated