Python — Arrays
What are Lists?
Lists are ordered, mutable collections that can hold any type of data:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True, 3.14]
Creating Lists
# Empty list
empty = []
# List literal
colors = ["red", "green", "blue"]
# Using list() constructor
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Accessing Elements
fruits = ["apple", "banana", "cherry", "date"]
fruits[0] # "apple" — first element
fruits[-1] # "date" — last element
fruits[1:3] # ["banana", "cherry"] — slice
fruits[:2] # ["apple", "banana"] — from start
fruits[2:] # ["cherry", "date"] — to end
fruits[::2] # ["apple", "cherry"] — every other
Modifying Lists
fruits = ["apple", "banana"]
# Change element
fruits[0] = "mango"
# Add to end
fruits.append("grape")
# Insert at index
fruits.insert(1, "orange")
# Extend with another list
fruits.extend(["kiwi", "peach"])
# Remove element
fruits.remove("banana")
# Remove by index
fruits.pop(0)
# Remove last
fruits.pop()
# Delete by index
del fruits[0]
# Clear all
fruits.clear()
List Methods
nums = [3, 1, 4, 1, 5, 9]
nums.sort() # [1, 1, 3, 4, 5, 9] — modifies in place
nums.reverse() # [9, 5, 4, 3, 1, 1]
nums.count(1) # 2
nums.index(4) # 2
nums.copy() # creates a copy
Iterating Over Lists
fruits = ["apple", "banana", "cherry"]
# Simple loop
for fruit in fruits:
print(fruit)
# With index
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
# With enumerate (Pythonic)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# With index and value
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
List Comprehensions
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# With transformation
names = ["alice", "bob"]
upper_names = [name.upper() for name in names] # ["ALICE", "BOB"]
# Nested
matrix = [[i*3+j+1 for j in range(3)] for i in range(3)]
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Flat list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in nested for num in row] # [1, 2, 3, 4, 5, 6]
Useful Operations
nums = [1, 2, 3, 4, 5]
# Length
len(nums) # 5
# Sum, min, max
sum(nums) # 15
min(nums) # 1
max(nums) # 5
# Check if exists
3 in nums # True
6 in nums # False
# Concatenation
[1, 2] + [3, 4] # [1, 2, 3, 4]
# Repetition
[0] * 5 # [0, 0, 0, 0, 0]
# Sorting
sorted(nums) # returns new sorted list
sorted(nums, reverse=True) # [5, 4, 3, 2, 1]
Unpacking
first, second, *rest = [1, 2, 3, 4, 5]
# first = 1, second = 2, rest = [3, 4, 5]
first, *middle, last = [1, 2, 3, 4, 5]
# first = 1, middle = [2, 3, 4], last = 5
Common Patterns
# Remove duplicates
unique = list(set([1, 1, 2, 3, 3])) # [1, 2, 3]
# Filter
even = list(filter(lambda x: x % 2 == 0, range(10)))
# Map
doubled = list(map(lambda x: x * 2, range(5)))
# Zip two lists
names = ["Alice", "Bob"]
scores = [95, 87]
paired = list(zip(names, scores)) # [("Alice", 95), ("Bob", 87)]
# Reverse
reversed_list = nums[::-1]
Mini Practice
- Create a list of 5 favorite movies
- Add and remove items from the list
- Sort the list alphabetically
- Use a list comprehension to filter movies by length
- Reverse the list using slicing
Up Next
Next: Tuples →
Related Topics
Frequently Asked Questions about Arrays
What is Arrays in Python?
Arrays is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Arrays?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.
Why is Arrays important in Python?
Arrays is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.