Introduction
"A list in Python is a data structure that stores a sequential collection of items, separated by commas. It is ordered, mutable, and offers various methods for manipulating content. Lists are essential for storing, processing, and manipulating data in various programming tasks, enclosed in square brackets '[]'."
Lists are ordered, which means that each element's place inside the list is meaningful and preserved.
Lists are changeable, which allows for the alteration of existing elements, the addition of new elements, and the removal of elements once the list has been created.
Indexing, slicing, adding, extending, inserting, and other operations are available for modifying the content of lists.
my_list = [element1, element2, ..., elementN]
my_list: This is the name you choose for your list variable.
element1, element2, ..., elementN: Elements can be of any data type and are separated by commas.
Today's blog includes the following topics and examples to level up your Python skills
Storing Different Types of Data in a List
Python lists can store elements of different data types, including numbers, strings, and even other lists.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
empty_list = []
numbers is a list of integers.
fruits is a list of strings.
mixed is a list containing elements of different data types.
empty_list is an empty list with no elements.
💡
Accessing elements in the
list using indices, modifying the
list, adding or removing elements, and performing various operations on it to manipulate your
data as needed.
Lists are a fundamental
data structure in
Python and are extensively used in programming for various tasks.
Creating Lists using range() Function
Make a list of integers by using the range() function, which returns a series of numbers inside a given range.
my_list = list(range(1, 6))
Example 1: Generate a list of dates for a calendar month
days_in_month = list(range(1, 31))
print(days_in_month)
The 'range(1, 31)' function creates values ranging from 1 to 30, indicating the days in a month.
Updating the Elements of a List
"Lists in Python are mutable*, which implies that their items can be* updated by accessing them via their indices."
my_list = [1,12,42,34,67,77]
my_list[2] = 42
Example 2: An inventory management system for a store
It simulates selling 10 units of "Widget A" and updates its quantity
inventory = [
{"product": "Widget A", "quantity": 50},
{"product": "Widget B", "quantity": 30},
{"product": "Widget C", "quantity": 20}
]
sold_quantity = 10
product_to_update = "Widget A"
for item in inventory:
if item["product"] == product_to_update:
item["quantity"] -= sold_quantity
for item in inventory:
print(f"{item['product']}: {item['quantity']} in stock")
"Concatenation of two lists in Python includes joining the elements of one list with the components of another list to generate a new, larger list."
Combine two lists using the + operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
Example 3: Different categories of products
electronics = ["Laptop", "Smartphone", "Tablet"]
clothing = ["T-Shirt", "Jeans", "Jacket"]
all_products = electronics + clothing
print("Available Products:")
for product in all_products:
print(product)
Concatenating two lists, 'electronics' and 'clothes', to create a new list, 'all_products', which includes all items in the store.
The * operator allows you to repeat a list by specifying the number of times you want to repeat it.
The resulting list will contain the elements of the original list repeated as many times as specified.
my_list = [0] * 3
Example 4: Weekly application scheduling team of employees
workweek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekly_schedule = workweek * 3
print("Weekly Schedule:")
for day in weekly_schedule:
print(day)
The * operator and 3 are used to repeat a workweek list three times, creating a weekly_schedule list covering three weeks, demonstrating the use of list repetition.
"Check if an element is present in a list using the in keyword."
my_list = [1, 4, 5, 7, 8, 3, 2]
if 3 in my_list:
print("3 is in the list")
Alias
Aliasing is the process of adding a new reference to an existing list.
In other words, two or more variables link to the same memory list object.
Changes to one variable affect the other variables referring to the same list.
list1 = [1, 2, 3]
list2 = list1
list1[0] = 0
print(list2)
Cloning
Cloning is the process of constructing a new list that contains the same entries as an existing list.
This may be accomplished by the use of slicing, the copy() function, or the list() constructor.
Changes made to the cloned list do not affect the original list.
list1 = [1, 2, 3]
list2 = list1[:]
list1[0] = 0
print(list2)
Example 5: To-do list
To create an alias, assign original_todo_list, while cloning the original list, changes to the cloned list do not affect the original list.
original_todo_list = ["Buy groceries", "Pay bills", "Finish report"]
alias_todo_list = original_todo_list
alias_todo_list.append("Call mom")
cloned_todo_list = list(original_todo_list)
cloned_todo_list.remove("Pay bills")
print("Original To-Do List:", original_todo_list)
print("Alias To-Do List:", alias_todo_list)
print("Cloned To-Do List:", cloned_todo_list)
Methods to Process Lists
Python provides several built-in methods to process and manipulate lists, including
append(): Add an element to the end of a list.
extend(): Extends a list with the elements from another iterable.
insert(): Inserts an element at a specific index.
remove(): Removes the first occurrence of a specified element.
pop(): Removes and returns an element by index.
clear(): Removes all elements from the list.
append(): Adds an element to the end of a list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
The append() method adds an element to the end of a list, like adding 4 to my_list, resulting in [1, 2, 3, 4].
extend(): Extends a list with the elements from another iterable.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
The extend() method adds elements from another iterable to a list, like list1, resulting in a single list with the elements from list2.
insert(): Inserts an element at a specific index.
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)
The insert() method inserts an element at a specified index in a list, like 4 at index 1, shifting existing elements accordingly.
remove(): Removes the first occurrence of a specified element.
my_list = [1, 2, 3, 2, 4]
my_list.remove(2)
print(my_list)
The remove() method is used to remove the first occurrence of a specified element from a list, such as 2.
pop(): Removes and returns an element by index.
my_list = [1, 2, 3, 4, 5]
element = my_list.pop(2)
print(element)
print(my_list)
The pop() method is used to remove and return an element at a specific index, as demonstrated in the example given.
clear(): Removes all elements from the list.
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list)
The pop() method is used to remove and return an element at a specific index, as demonstrated in the example given.
Finding the Biggest and Smallest Elements in a List
To get the greatest and smallest members in a list, use the 'max()' and 'min()' methods.
largest = max(my_list)
smallest = min(my_list)
Example 5: Finding the Tallest
student_heights = [160, 175, 155, 180, 168, 162, 170]
tallest_student = max(student_heights)
shortest_student = min(student_heights)
print(f"The tallest student is {tallest_student} cm tall.")
print(f"The shortest student is {shortest_student} cm tall.")
'max(student_heights)' returns the tallest student and'min(student_heights)' returns the smallest student from the'student_heights' list.
The sort() method modifies a list in place, sorting it in ascending order by default.
The sorted() function takes an iterable as input and returns a new sorted list, maintaining the original order.
Custom sorting can be done using the reverse and key arguments. Both methods are non-destructive.
my_list.sort()
sorted_list = sorted(my_list)
Example 6: List of student records
student_records = [
{"name": "Alice", "score": 92},
{"name": "Bob", "score": 85},
{"name": "Charlie", "score": 98},
{"name": "David", "score": 78},
{"name": "Eve", "score": 89},
]
student_records.sort(key=lambda x: x["score"])
print("Sorted by exam score (ascending order):")
for record in student_records:
print(f"{record['name']}: {record['score']}")
sorted_records = sorted(student_records, key=lambda x: x["score"], reverse=True)
print("\nSorted by exam score (descending order):")
for record in sorted_records:
print(f"{record['name']}: {record['score']}")
The sorted() method was utilized to sort student records in ascending order of exam scores, and a new sorted list in descending order, enabling easy identification of the highest-scoring students.
Number of Occurrences of an Element in the List
"Count the occurrences of an element in a list using the count() method."
count = my_list.count(2)
Finding Common Elements in Two Lists
"Finding the common elements between two lists using list comprehension or the intersection() method."
common_elements = [x for x in list1 if x in list2]
common_elements = list(set(list1).intersection(list2))
Nested Lists as Matrices
"Create lists of lists, which are called nested lists."
Nested lists in Python are lists of lists, containing other lists as elements, used to represent complex data structures or tables where each element in the outer list is itself a list.
To express matrices or multi-dimensional arrays, utilize layered lists.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
element = matrix[1][1]
print(element)
The code selects the second inner list from the second inner list, '[4, 5, 6]'.
Nested lists are versatile and can be used to represent various data structures, such as tables, grids, or hierarchical data. They are commonly used in applications involving matrices, game boards, and more complex data structures.
"List comprehensions provide a concise way to create lists based on existing lists."
numbers = [1, 2, 3, 4, 5]
odd_numbers = [x for x in numbers if x % 2 != 0]
print(odd_numbers)[1, 3, 5]
[1, 3, 5]
Comprehensions in Python allow for the creation of new lists by applying an expression to each item in an existing iterable and optionally filtering the items based on a condition.
Summary
Python lists are essential data structures in programming, offering various operations and use cases. They can be created using the
range() function,
updated using indices, combined using the
+ operator,
repeated using the
* operator, and aliased and
cloned using slicing or the
list() constructor. They can store different types of data, create nested
lists for complex structures, and use
list comprehensions for filtering and transformation.