Python List Basics: A Complete Guide
Lists are one of the most versatile and commonly used data structures in Python. They provide a convenient way to store, modify, and process collections of data. Whether you're a beginner or an experienced developer, mastering Python lists is essential for all areas of software development.
This article covers everything you need to know: creating Python lists, adding and removing elements, and efficient ways to work with this powerful data structure.
What is a List in Python?
Definition and Key Features
A list is an ordered, mutable collection of objects. It can hold elements of different types, including integers, strings, nested lists, and even functions.
my_list = [1, 2, 3, "Python", True]
The key feature of lists is that you can modify their contents after creation. This mutability sets them apart from tuples and makes them ideal for dynamic data.
Indexing and Accessing Elements
List elements are indexed starting from zero. Access a specific element using square brackets:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last element)
How to Create Lists in Python
Creating an Empty List
Initialize an empty list in two ways:
empty_list = []
# or
empty_list = list()
Creating a List with Initial Elements
Declare a list directly with starting values:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
Using the list() Constructor
The list() function converts iterable objects into lists:
numbers = list(range(5)) # [0, 1, 2, 3, 4]
string_list = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
Creating Lists with Repeated Elements
The multiplication operator lets you create lists with duplicate values:
zeros = [0] * 5 # [0, 0, 0, 0, 0]
pattern = ["a", "b"] * 3 # ['a', 'b', 'a', 'b', 'a', 'b']
Adding Elements to a List
append() - Add a Single Element
The append() method adds a new element to the end of the list:
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
Important: append() adds the element as a whole, even if it's a list:
main_list = [1, 2, 3]
main_list.append([4, 5])
print(main_list) # [1, 2, 3, [4, 5]]
extend() - Add Multiple Elements
extend() expands the list with elements from an iterable:
fruits = ["apple", "banana"]
fruits.extend(["cherry", "orange", "grape"])
print(fruits) # ['apple', 'banana', 'cherry', 'orange', 'grape']
It works with any iterable:
numbers = [1, 2]
numbers.extend(range(3, 6)) # adds 3, 4, 5
numbers.extend("abc") # adds 'a', 'b', 'c'
insert() - Insert at a Specific Index
insert() places an element at a given position:
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "kiwi")
print(fruits) # ['apple', 'kiwi', 'banana', 'cherry']
If the index is greater than the list length, the element is added at the end.