Creating and Manipulating Lists
Lists are one of the most versatile data structures in Python. A list is an ordered, mutable collection that can hold items of any type. Lists are defined using square brackets.
You can access individual items by their index (starting at 0), use negative indices to count from the end, and slice lists the same way you slice strings.
Example
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []
# Accessing elements
print(fruits[0]) # apple (first item)
print(fruits[-1]) # cherry (last item)
print(fruits[1:3]) # ['banana', 'cherry'] (slice)
# Modifying lists
fruits[1] = "blueberry" # Change an item
print(fruits) # ['apple', 'blueberry', 'cherry']
# List methods
fruits.append("date") # Add to end
fruits.insert(1, "banana") # Insert at index 1
fruits.remove("cherry") # Remove by value
popped = fruits.pop() # Remove and return last item
print(fruits) # ['apple', 'banana', 'blueberry']
print(popped) # date
# Length
print(len(fruits)) # 3 - .append(item) — Add an item to the end of the list
- .insert(index, item) — Insert an item at a specific position
- .remove(item) — Remove the first occurrence of a value
- .pop(index) — Remove and return an item (default: last item)
- .sort() — Sort the list in place
- .reverse() — Reverse the list in place
- len(list) — Return the number of items in the list
Try List Operations
JavaScript
fruits = ["apple", "banana", "cherry"]
print("Original:", fruits)
fruits.append("date")
print("After append:", fruits)
fruits.remove("banana")
print("After remove:", fruits)
fruits.sort()
print("Sorted:", fruits)
print("Length:", len(fruits)) Notes
- Lists are mutable — you can change their contents after creation. This is different from strings and tuples, which are immutable.
List Comprehensions
List comprehensions provide a concise way to create new lists by applying an expression to each item in an existing sequence. They replace the need for a multi-line for loop in many common cases.
The basic syntax is: [expression for item in iterable if condition]. The condition part is optional.
Example
# Traditional approach
squares = []
for x in range(1, 6):
squares.append(x ** 2)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension — same result, one line
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With a condition (filter)
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# String manipulation
names = ["alice", "bob", "charlie"]
capitalized = [name.capitalize() for name in names]
print(capitalized) # ['Alice', 'Bob', 'Charlie']
# Nested comprehension — flatten a 2D list
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6] Try List Comprehensions
JavaScript
# Create squares of 1 to 5
squares = [x ** 2 for x in range(1, 6)]
print("Squares:", squares)
# Filter: only even numbers from 1-20
evens = [x for x in range(1, 21) if x % 2 == 0]
print("Evens:", evens)
# Capitalize names
names = ["alice", "bob", "charlie"]
print([n.upper() for n in names]) Notes
- List comprehensions are more Pythonic and often faster than equivalent for loops. However, keep them simple — if the logic gets complex, a regular for loop is more readable.
