Lists are one of the most commonly used data structures in Python. They are versatile, mutable, and allow you to store multiple items in a single variable. This article explains how to define lists and access their elements with examples.
A list in Python is an ordered collection of items, which can be of different data types. Lists are defined using square brackets []
, and elements are separated by commas.
Lists can contain any combination of integers, strings, floats, or even other lists.
# Defining lists empty_list = [] # An empty list numbers = [1, 2, 3, 4, 5] # List of integers mixed = [1, "hello", 3.14, True] # Mixed data types nested = [[1, 2], [3, 4]] # List of lists print("Empty list:", empty_list) print("Numbers:", numbers) print("Mixed:", mixed) print("Nested:", nested)
You can access individual elements in a list using their index. Python uses zero-based indexing, so the first element has an index of 0
.
# Accessing elements by index numbers = [10, 20, 30, 40, 50] print("First element:", numbers[0]) # 10 print("Second element:", numbers[1]) # 20 print("Last element:", numbers[-1]) # 50 (negative index)
Slicing allows you to access a subset of elements from a list. The syntax is list[start:end]
, where start
is inclusive, and end
is exclusive.
# Slicing a list numbers = [10, 20, 30, 40, 50] print("First three elements:", numbers[0:3]) # [10, 20, 30] print("Elements from index 2 onwards:", numbers[2:]) # [30, 40, 50] print("All except the last:", numbers[:-1]) # [10, 20, 30, 40]
Lists are mutable, so you can change the value of an element by assigning a new value to its index.
# Modifying elements numbers = [10, 20, 30, 40, 50] numbers[0] = 100 # Change first element print("After modification:", numbers) # [100, 20, 30, 40, 50]
You can use a for
loop to iterate through each element in a list.
# Iterating through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("Fruit:", fruit)
Python provides various operations and functions to work with lists.
# List operations numbers = [10, 20, 30] # Add an element numbers.append(40) print("After appending:", numbers) # [10, 20, 30, 40] # Remove an element numbers.remove(20) print("After removing 20:", numbers) # [10, 30, 40] # Check if an element exists print("Is 30 in the list?", 30 in numbers) # True # Length of the list print("Length of the list:", len(numbers)) # 3
You can have lists within lists, called nested lists. Access elements in nested lists using multiple indices.
# Nested list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("First row:", matrix[0]) # [1, 2, 3] print("Element at row 2, column 3:", matrix[1][2]) # 6
Lists are a fundamental data structure in Python, providing a flexible and powerful way to manage collections of data. By mastering list operations, you can efficiently handle various programming tasks.