Python Basics — Creating & Accessing Lists
Creating & Accessing Lists
A list is an ordered collection of items enclosed in square brackets []. Lists can hold any data type, and items can be different types.
Creating Lists
# Empty list
empty = []
also_empty = list()
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List of strings
fruits = ["apple", "banana", "cherry"]
# Mixed types
mixed = [1, "hello", 3.14, True, None]
# From range
nums = list(range(1, 6)) # [1, 2, 3, 4, 5]
# From a string
chars = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
Indexing
Lists use zero-based indexing, just like strings:
fruits = ["apple", "banana", "cherry", "date"]
# Positive indexing
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[3]) # date
# Negative indexing
print(fruits[-1]) # date
print(fruits[-2]) # cherry
Index: 0 1 2 3
["apple", "banana", "cherry", "date"]
Neg: -4 -3 -2 -1
Modifying Elements
Unlike strings, lists are mutable:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
Built-in Functions with Lists
numbers = [4, 2, 8, 1, 5]
print(len(numbers)) # 5
print(min(numbers)) # 1
print(max(numbers)) # 8
print(sum(numbers)) # 20
print(sorted(numbers)) # [1, 2, 4, 5, 8] (returns new list)
Checking Membership
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("grape" in fruits) # False
print("grape" not in fruits) # True
Empty Lists and Truthiness
empty = []
full = [1, 2, 3]
print(bool(empty)) # False (empty list is falsy)
print(bool(full)) # True
# Pythonic way to check if a list has items
if fruits:
print("List has items")
else:
print("List is empty")
List Repetition and Concatenation
# Concatenation
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c) # [1, 2, 3, 4, 5, 6]
# Repetition
zeros = [0] * 5
print(zeros) # [0, 0, 0, 0, 0]
# Caution with mutable elements!
matrix = [[0]] * 3 # [[0], [0], [0]] — all point to the SAME inner list!
matrix[0][0] = 1
print(matrix) # [[1], [1], [1]] — all changed!
# Safe way
matrix = [[0] for _ in range(3)]
matrix[0][0] = 1
print(matrix) # [[1], [0], [0]] — only first changed
Iterating Over Lists
fruits = ["apple", "banana", "cherry"]
# Simple iteration
for fruit in fruits:
print(fruit)
# With index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Using range (less Pythonic)
for i in range(len(fruits)):
print(fruits[i])
Summary
- Create lists with
[],list(), orlist(range(...)) - Access elements with positive
[0]or negative[-1]indexing - Lists are mutable — elements can be changed in place
- Use
len(),min(),max(),sum()for common operations - Use
into check membership - Empty lists are falsy; non-empty lists are truthy
- Be careful with
[[]] * n— use comprehensions for independent inner lists
Next up: List Methods →