Syntax
[item1, item2, item3]Examples
Creating and Accessing Lists
Building a list and reading elements by index.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
print(len(fruits)) # 3Modifying Lists
Adding, inserting, and removing items.
fruits = ["apple", "banana"]
fruits.append("cherry") # add to the end
fruits.insert(1, "blueberry") # insert at index 1
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry']
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return the last item
print(fruits, popped)Sorting and Reversing
Ordering list contents in place or as a new list.
numbers = [4, 1, 3, 2]
numbers.sort() # sorts in place, ascending
print(numbers) # [1, 2, 3, 4]
numbers.sort(reverse=True)
print(numbers) # [4, 3, 2, 1]
original = [3, 1, 2]
new_sorted = sorted(original) # returns a new list, leaves original unchanged
print(original, new_sorted)List Operations
Combining lists and checking membership.
a = [1, 2, 3]
b = [4, 5]
combined = a + b # concatenation
print(combined) # [1, 2, 3, 4, 5]
repeated = [0] * 3
print(repeated) # [0, 0, 0]
print(3 in a) # True
print(10 in a) # FalseBest practices
- Use lists when the collection may grow, shrink, or be reordered; use a tuple instead for fixed, unchanging data
- Use .append() to add single items and .extend() to add all items from another iterable, not += for large loops
- Prefer sorted() when you need the original list preserved, and .sort() when modifying in place is fine
- Avoid using list as a variable name - it shadows the built-in list() type
- Use list comprehensions instead of building a list with a loop and repeated .append() calls, when the transformation is simple
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference