Hey programmers! In the last lessons, you mastered control flow and loop constructs to efficiently decide which block to run and for how many times. You can now tell your code to react to different scenarios and perform repetitive tasks without writing redundant code. But what if you have a collection of related data and you want to store it? One approach would be creating individual variables for each value. But, a better approach would be using data structures.
The data structures are specialized formats to store and organize data in a way that allows you to access and modify it efficiently. In this article, we will learn about Python's most basic yet widely used data structures, i.e., lists and tuples.
Lists in Python
A list is an ordered collection of heterogeneous items. For example, a shopping list is arranged in a particular order. The items in a list do not have to belong to a particular type. Instead, you can store multiple types of items in it. Also, the lists in Python are mutable, meaning that you can make changes to your lists dynamically. You can add items, remove them, and make changes to the existing ones.
Declaring and Initializing Lists in Python
Syntax:
list_name = [] # An empty list
list_name =[item_1, item_2, item_3, ..., item_N] # A list with 'n' number of items.
Example:
numbers = [1, 2, 3, 4, 5]
fruits = ["Apple", "Banana", "Orange", "Mango"]
Accessing List Items
The list items are accessed using the index number. The index starts from 0 and ends at number_of_items – 1. For example, if there are 5 items in a list, its index will range from 0 to 4.
Syntax:
list_name[index]
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
print(fruits[2]) # Prints Orange
Output:
Orange
Negative Indexing
If you want to access a list from the end, you can use the negative indexing as follows:
Syntax:
list_name[-index]
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
print(fruits[-1]) # Prints Mango
print(fruits[-2]) # Prints Orange
Output:
Mango
Orange
Slicing
Another way to access a list is with slicing. It is a process of creating a sub-list from a list.
Syntax:
list_name[start:end]
In the above syntax, the start index is inclusive, and the end is exclusive.
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
print(fruits[1:3]) # Prints Banana, and Orange
Output:
['Banana', 'Orange']
Changing List Elements
If you want to modify the existing list elements, you can also do that using the index numbers.
Syntax:
list_name[index] = new_value # Assigns new value to the specified index number.
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
fruits[1] = "Grapes"
print(fruits[1]) # Prints Grapes instead of Banana
Output:
Grapes
Adding New Elements to the List
You can also add new items to the list anywhere in the program after the list declaration.
Adding Items to the End
Syntax:
list_name.append(item)
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
fruits.append("Grapes")
fruits.append("Fig")
print(fruits) # Prints the entire list.
Output:
['Apple', 'Banana', 'Orange', 'Mango', 'Grapes', 'Fig']
Adding Items At an Index
Syntax:
list_name.insert(index, item)
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
fruits.insert(1, "Grapes") # Inserts Grapes in place of Banana and moves Banana to the right
print(fruits) # Prints the entire list.
Output:
['Apple', 'Grapes', 'Banana', 'Orange', 'Mango']
Add Items From One List to Another
Syntax:
list_name.extend(list2)
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
berries = ["Strawberries", "Blueberries"]
fruits.extend(berries) # Inserts the items of Berries list to the fruits list.
print(fruits) # Prints the entire list.
Output:
['Apple', 'Banana', 'Orange', 'Mango', 'Strawberries', 'Blueberries']
Removing Elements From a List
Besides extending lists, you can also remove elements from them.
Removing Item From a Specific Index
Syntax:
del listname[index]
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
del fruits[1] #Deletes Banana from the list
print(fruits) # Prints the entire list.
Output:
['Apple', 'Orange', 'Mango']
Removing Item by Value
Syntax:
list_name.remove(item)
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
fruits.remove("Orange") #Deletes Orange from the list
print(fruits) # Prints the entire list.
Output:
['Apple', 'Banana', 'Mango']
Removing All the Items from a List
Syntax:
list_name.clear()
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
fruits.clear() # Deletes all items from the list
print(fruits) # Prints an empty list.
Output:
[]
Finding the Number of Items in a List
If you want to find the number of items in a list, you can use the len()
function as follows:
Syntax:
len(list_name)
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
print(len(fruits)) # 4
Output:
4
Finding the Index of an Item
You can find the position of an item in a list using the index()
method.
Syntax:
list_name.index(item)
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
print(fruits.index("Orange")) # 2
Output:
2
Iterating Through Lists
If you want to go through a list, you can use the 'for' loop as follows:
Syntax:
for variable in list_name:
statements
Example:
fruits = ["Apple", "Banana", "Orange", "Mango"]
for fruit in fruits: # Iterates through the fruits list
if fruit == "Orange": # Checks if the fruit is Orange
break # Terminates the loop
else:
print(fruit)
Output:
Apple
Banana
Tuples in Python
Tuples are also a collection of ordered items that are immutable, meaning that once a tuple has been declared, you cannot make changes to it. This immutability makes tuples useful for collections that must remain constant throughout the program.
Declaring and Initializing Tuples
Syntax:
tuple_name = (item1, item2, item3, ..., itemN) #A tuple with N items
Example:
colors = ("red", "green", "blue")
Accessing Tuples
You can access the tuples, same as lists. The elements in a tuple are identified with the index numbers starting from 0 and ending in 1 less than the total number of elements.
Syntax:
colors = ("red", "green", "blue")
print(colors[1]) # Prints Green
Output:
green
Bingo! You have unlocked two powerful ways to organize your data in Python, i.e., lists that are ordered and mutable collections perfect for storing dynamic data and tuples that are organized and immutable, well-suited for storing constant data. With these data structures, you can handle and manipulate structured data in your programs. In the next article, we will dive deep into dictionaries and sets.