Python List
Python Lists: A Complete Introduction
Lists are one of the most versatile and commonly used data types in Python. They allow you to store and manipulate a collection of items in a single variable.
What Is a List?
A list is an ordered collection of items that can hold elements of any data type - strings, numbers, other lists, or even mixed types.
my_list = [1, 2, 3, "hello", [4, 5]]- Lists are mutable, meaning you can change their contents after creation.
- They are defined using square brackets
[]. - Each element is separated by a comma.
Creating a List
You can create an empty list or a list with elements:
empty_list = []
numbers = [10, 20, 30]
fruits = ["apple", "banana", "cherry"]Accessing Elements in a List
You can access elements using indexing, where the first element has index 0:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherryYou can also use negative indexing to access elements from the end:
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: bananaModifying a List
Lists are mutable, so you can change their content:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']Common List Operations
Here are some useful operations and methods for working with lists:
Adding Elements
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']Removing Elements
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry']
popped = fruits.pop()
print(popped) # Output: cherry
print(fruits) # Output: ['apple']Slicing a List
You can extract a portion of a list using slicing:
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [1, 2, 3]
print(numbers[:3]) # Output: [0, 1, 2]
print(numbers[3:]) # Output: [3, 4, 5]Iterating Through a List
You can use a for loop to go through each item:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherryChecking for Membership
Use in to check if an item is in the list:
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
print("grape" in fruits) # Output: FalseList Comprehension
List comprehension is a concise way to create lists:
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]This is equivalent to:
squares = []
for x in range(5):
squares.append(x**2)Sorting and Reversing
You can sort and reverse lists easily:
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
numbers.reverse()
print(numbers) # Output: [4, 3, 2, 1]Note: sort() modifies the list in-place. Use sorted(numbers) to get a new sorted list.
Nested Lists
Lists can contain other lists:
matrix = [
[1, 2],
[3, 4],
[5, 6]
]
print(matrix[1]) # Output: [3, 4]
print(matrix[1][0]) # Output: 3Useful List Functions
len(list)– number of elementsmax(list)– largest item (numbers or alphabetical)min(list)– smallest itemsum(list)– sum of all elements (if numeric)
numbers = [10, 20, 30]
print(len(numbers)) # Output: 3
print(sum(numbers)) # Output: 60Summary
- Lists are ordered, mutable collections.
- You can access, modify, slice, and iterate through them.
- Use methods like
append(),insert(),remove(), andpop()for common tasks. - List comprehension makes list creation concise and powerful.
- You can sort, reverse, and nest lists for more advanced structures.
Understanding lists is essential to mastering Python. They're foundational for almost every project or script you'll write.