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 stringsAccessing 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
List Comprehension
Other Useful List Operations
Concatenating Lists
Removing Duplicates
Counting Occurrences
Extending a List
Clearing a List
List as Stack
Last updated