Data Structures: Lists
Learn about lists, a versatile data structure for storing ordered collections of items. Covers creation, access, modification, and common list methods.
Data Structures: Lists in Python
Introduction to Lists
Lists are a fundamental and versatile data structure in Python. They are used to store ordered collections of items. This means the order in which you add elements to a list is preserved.
Lists are mutable, meaning you can change their contents after they are created. They can contain items of different data types, including numbers, strings, other lists, and objects.
Creating Lists
You can create a list using square brackets []
. Items within the list are separated by commas.
# Creating an empty list
my_list = []
# Creating a list of integers
numbers = [1, 2, 3, 4, 5]
# Creating a list of strings
fruits = ["apple", "banana", "cherry"]
# Creating a list with mixed data types
mixed_list = [1, "hello", 3.14, True]
Accessing List Elements
You can access individual elements in a list using their index. List indices start at 0 for the first element.
fruits = ["apple", "banana", "cherry"]
# Accessing the first element (apple)
first_fruit = fruits[0]
print(first_fruit) # Output: apple
# Accessing the second element (banana)
second_fruit = fruits[1]
print(second_fruit) # Output: banana
# Accessing the last element (cherry)
last_fruit = fruits[2]
print(last_fruit) # Output: cherry
# Negative indexing: Accessing the last element
last_fruit = fruits[-1]
print(last_fruit) # Output: cherry
# Negative indexing: Accessing the second to last element
second_to_last = fruits[-2]
print(second_to_last) # Output: banana
Modifying Lists
Lists are mutable, so you can change their contents after they are created. You can modify elements by assigning new values to specific indices.
fruits = ["apple", "banana", "cherry"]
# Changing the first element
fruits[0] = "grape"
print(fruits) # Output: ['grape', 'banana', 'cherry']
# Changing the second element
fruits[1] = "orange"
print(fruits) # Output: ['grape', 'orange', 'cherry']
Common List Methods
Python provides several built-in methods for working with lists. Here are some of the most commonly used ones:
append(item)
: Adds an item to the end of the list.insert(index, item)
: Inserts an item at a specific index.remove(item)
: Removes the first occurrence of a specified item.pop(index)
: Removes and returns the item at the specified index (defaults to the last item).index(item)
: Returns the index of the first occurrence of a specified item.count(item)
: Returns the number of times an item appears in the list.sort()
: Sorts the list in ascending order (modifies the list in place).reverse()
: Reverses the order of the list (modifies the list in place).len(list)
: Returns the number of items in the list.clear()
: Removes all items from the list.extend(iterable)
: Extends the list by appending all the items from an iterable (e.g., another list, tuple, or string).
# Using list methods
numbers = [1, 2, 3]
# Appending an item
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
# Inserting an item at index 1
numbers.insert(1, 10)
print(numbers) # Output: [1, 10, 2, 3, 4]
# Removing the item 2
numbers.remove(2)
print(numbers) # Output: [1, 10, 3, 4]
# Popping the item at index 1
popped_item = numbers.pop(1)
print(popped_item) # Output: 10
print(numbers) # Output: [1, 3, 4]
# Finding the index of 3
index_of_3 = numbers.index(3)
print(index_of_3) # Output: 1
# Counting the number of times 1 appears
count_of_1 = numbers.count(1)
print(count_of_1) # Output: 1
# Sorting the list
numbers.sort() # sorts in place
print(numbers) # Output: [1, 3, 4]
# Reversing the list
numbers.reverse() # reverses in place
print(numbers) # Output: [4, 3, 1]
#Getting the length of the list
length_of_numbers = len(numbers)
print(length_of_numbers) #Output: 3
#Clearing the list
numbers.clear()
print(numbers) #Output: []
#Extending a list
list1 = [1,2,3]
list2 = [4,5,6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
List Slicing
List slicing allows you to create a new list containing a portion of an existing list. The syntax is list[start:end:step]
.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from index 2 to 5 (exclusive of 5)
slice1 = numbers[2:5]
print(slice1) # Output: [2, 3, 4]
# Slice from the beginning to index 3 (exclusive of 3)
slice2 = numbers[:3]
print(slice2) # Output: [0, 1, 2]
# Slice from index 6 to the end
slice3 = numbers[6:]
print(slice3) # Output: [6, 7, 8, 9]
# Slice with a step of 2
slice4 = numbers[1:8:2]
print(slice4) #Output: [1, 3, 5, 7]
# Create a copy of the list
slice5 = numbers[:]
print(slice5) #Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#Reverse the list using slicing
reversed_list = numbers[::-1]
print(reversed_list) #Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
List Comprehensions
List comprehensions provide a concise way to create lists. They are often more readable and efficient than using traditional for
loops to build lists.
# Example: Creating a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Example: Creating a list of even numbers from 0 to 19
even_numbers = [x for x in range(20) if x % 2 == 0]
print(even_numbers) #Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Example: Using conditional logic within the expression
numbers = [1, 2, 3, 4, 5]
results = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(results) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']