How do I create and manipulate lists in Python?
· Category: Python Programming
Short answer
A Python list is a mutable, ordered collection that can hold items of mixed types. You create lists with square brackets, access items by index, and modify them with methods like .append(), .extend(), .insert(), .remove(), and .pop().
Steps
- Create a list:
my_list = [1, 2, 3]. - Access or slice items:
my_list[0],my_list[1:3]. - Modify with methods or assignment.
items = ["apple", "banana"]
items.append("cherry")
items.insert(1, "blueberry")
items.remove("banana")
popped = items.pop()
print(items)
print(popped)
Tips
- List comprehensions provide a concise way to create lists:
[x*2 for x in range(5)]. - Use
.copy()or slicing[:]to create a shallow copy. sorted(list)returns a new sorted list;.sort()sorts in place.- Checking membership with
inis O(n); for frequent lookups, consider aset.
# List comprehension
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
# Sorting
words = ["banana", "pie", "Washington"]
words.sort(key=len)
print(words)
Common issues
- Modifying a list while iterating over it can cause skipped items or runtime errors.
- Using
=to copy a list creates a reference, not an independent copy. .remove()only removes the first matching item; use a loop or list comprehension to remove all occurrences.