Python List Tutorial
Introduction:
Lists are one of the most commonly used data structures in Python. A list is a collection of elements, which can be of any type, including numbers, strings, and other lists etc. Lists are mutable, which means you can make changes in the list by adding, removing, or changing elements.
List declaration:
To declare a list in Python, you can use square brackets [] and separate the elements with commas. Here’s an example:
new_list = [ 1, 2, 3, 4, 5 ]
In the above example, we created a list called new_list that contains five integers.
You can also create an empty list by using the list() function or just an empty set of square brackets []. Here are some examples:
list_1 = list()
list_2 = []
Both of the examples above create an empty list called empty_list_1 and list_2.
You can also create a list of a specific size filled with a default value using the * operator. Here’s an example:
empty_list_1 = []
empty_list_2 = list()
In the example above, we created a list called my_list that contains three 1 values.
my_list = [1, 1, 1]
List Rules:
- List elements can be of different data types, including integers, floats, strings, booleans, and other objects.
- Lists are mutable, which means that we can modify it by adding, removing, or changing elements.
- Index of elements in the list starts from 0. We can access individual elements of a list by their index.
- We can use slicing to extract a subset of elements from a list. Slicing returns a new list that includes the specified range of elements.
- Lists can be concatenated using the ‘+’ operator.
- Lists can be nested, meaning that you can have a list of lists.
- Lists can be sorted in ascending or descending order using the sorted() function or the sort() method.
- We can use the len() function to get the number of elements in a list.
- We can iterate over the elements of a list using a for loop or list comprehension.
- Two lists can be compared for equality using the ‘==’ operator. Two lists are considered equal if they have the same elements in the same order.
Python list features:
- Mutable: Lists are mutable, meaning you can modify their elements by assigning new values to specific indices.
- Ordered: Lists maintain the order of elements as they are added. The first element added will be at index 0, the second element at index 1, and so on.
- Dynamic Size: Python lists can dynamically grow or shrink in size as elements are added or removed. You don’t need to specify the size beforehand.
- Heterogeneous Elements: Lists can contain elements of different data types. For example, a single list can store integers, floats, strings, or even other lists.
- Indexing and Slicing: You can access individual elements in a list using square brackets notation and their index. Additionally, you can slice lists to extract a portion of elements by specifying start and end indices.
- Iteration: Lists can be easily iterated over using loops or list comprehensions, allowing you to process each element or perform operations on the entire list.
- Built-in Functions: Python provides a range of built-in functions specifically designed for working with lists. These include functions like `len()`, `max()`, `min()`, `sum()`, `sorted()`, and more.
- Versatile Data Structure: Lists are a versatile data structure used in a variety of scenarios. They are commonly used for storing collections of related items, implementing stacks, queues, and other data structures, and for general-purpose data manipulation.
- List Comprehensions: Python allows you to create new lists by performing operations on existing lists using concise and expressive syntax called list comprehensions. This feature provides an efficient and readable way to manipulate lists.
- Extensive Methods: Python lists come with a range of built-in methods that enable various operations like adding or removing elements, sorting, reversing, searching, and more. These methods make it easy to work with lists and perform common list operations efficiently.
Python list advantages:
- Flexibility: Python lists are highly flexible and versatile. They can store elements of different data types, allowing you to create lists with a mix of integers, floats, strings, and other objects. This flexibility makes lists suitable for a wide range of applications.
- Dynamic Size: Lists in Python can grow or shrink dynamically as elements are added or removed. Unlike some other programming languages, you don’t need to specify the size of a list beforehand. This dynamic resizing capability makes it convenient to work with collections of varying lengths.
- Easy Element Manipulation: Python provides intuitive ways to manipulate list elements. You can easily access, modify, or delete elements based on their indices. This makes it convenient to update or rearrange elements within a list as needed.
- Iteration and Looping: Python lists can be easily iterated over using loops or list comprehensions. This allows you to process each element in a list sequentially or apply operations to the entire list, making it straightforward to perform calculations or transformations on list data.
- Built-in Functions and Methods: Python provides a rich set of built-in functions and methods specifically designed for working with lists. These functions and methods simplify common list operations such as sorting, searching, filtering, adding or removing elements, and more. This extensive set of tools saves you time and effort when working with lists.
- Powerful List Comprehensions: Python offers list comprehensions, which are concise and expressive ways to create new lists based on existing ones. List comprehensions allow you to apply transformations, conditions, and calculations to existing lists in a single line of code, making your code more readable and compact.
- Compatibility with Other Data Structures: Lists in Python can easily be converted to and from other data structures like tuples or arrays. This compatibility allows you to take advantage of the specific features and benefits offered by different data structures as needed.
- Common Data Structure: Python lists are widely used and well-supported. They are a fundamental data structure in Python, and you’ll find them extensively used in libraries, frameworks, and code examples. This popularity means that there is a wealth of resources, documentation, and community support available for working with lists.
Python list disadvantages:
- Slow for Large Data Sets: Python lists may become inefficient when dealing with large data sets or performing operations that require frequent insertions or deletions. As lists are dynamically resized, these operations can be time-consuming, particularly if the list needs to be resized multiple times.
- Sequential Search: When searching for an element in a list, Python performs a sequential search, iterating through each element until a match is found. This linear search approach can be slow for large lists, especially when compared to more efficient search algorithms like binary search available for sorted arrays.
- Fixed Overhead: Each element in a Python list requires additional memory to store its value and associated metadata, such as the data type and object reference. This fixed overhead per element can be significant when dealing with large lists, potentially consuming more memory than other data structures optimized for memory efficiency.
- Lack of Constant-Time Operations: Certain operations on Python lists, such as inserting or removing an element at a specific index, can be slow for large lists. These operations may require shifting or reassigning elements, resulting in a time complexity of O(n), where n is the number of elements in the list. In contrast, other data structures like arrays or linked lists can provide constant-time operations for these operations.
- Limited Sorting Options: Python’s built-in sorting method, `list.sort()`, uses a variant of the quicksort algorithm. While it is efficient in most cases, it may not be suitable for certain specialized sorting requirements. For such scenarios, you may need to implement custom sorting algorithms or explore external libraries for specific sorting needs.
- Not Suitable for Unique Elements: Python lists can contain duplicate elements. If you require a collection that only allows unique elements, you need to perform additional checks or use alternative data structures like sets or dictionaries.
- Mutable Nature: While mutability can be an advantage, it can also lead to unintended changes in list elements. If a list is shared among multiple parts of a program or passed as a parameter to functions, modifying the list can affect other parts of the code unintentionally. This can lead to potential bugs or unexpected behavior.
Python List Indexing and Slicing
In Python first element in the list has an index of 0. You can access elements in a list by their index using square brackets. Here’s an example:
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Access the first element
first_element = my_list[0] # 'apple'
# Access the second element
second_element = my_list[1] # 'banana'
# Access the third element
third_element = my_list[2] # 'cherry'
# Print the elements
print("First element:", first_element)
print("Second element:", second_element)
print("Third element:", third_element)
You can also use negative indexing to access the list elements in the reverse order. Here’s an example:
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Access the last element
last_element = my_list[-1] # 'cherry'
# Access the second-to-last element
second_last_element = my_list[-2] # 'banana'
# Access the third-to-last (or first) element
third_last_element = my_list[-3] # 'apple'
# Print the elements
print("Last element:", last_element)
print("Second-to-last element:", second_last_element)
print("Third-to-last element:", third_last_element)
Slicing rules to created sublist in python:
Here are the rules for slicing in Python:
- Slicing uses the colon : operator to specify a range of indices. The syntax is my_list[start_index:end_index:step].
- The start_index is the index of the first element to include in the slice. If not specified, it defaults to 0.
- The end_index is the index of the first element to exclude from the slice. If not specified, it defaults to the length of the list.
- The step parameter specifies the step size between elements in the slice. If not specified, it defaults to 1.
- All parameters can be negative, in which case they specify the index relative to the end of the list. For example, my_list[-1] refers to the last element of the list.
- Slicing returns a new list that contains the specified range of elements from the original list.
You can also use slicing to access a subset of the list. Slicing allows you to extract a range of elements from the list. Here’s an example:
# Define a list
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Slice to get the first three elements
first_three = my_list[0:3] # ['apple', 'banana', 'cherry']
# Slice to get elements from index 2 to the end
from_second_onwards = my_list[2:] # ['cherry', 'date', 'elderberry']
# Slice to get the last two elements
last_two = my_list[-2:] # ['date', 'elderberry']
# Slice with a step of 2 (every second element)
every_second = my_list[::2] # ['apple', 'cherry', 'elderberry']
# Print the results
print("First three elements:", first_three)
print("From second onwards:", from_second_onwards)
print("Last two elements:", last_two)
print("Every second element:", every_second)
In the example above, we used slicing to extract a subset of the list that starts at index 0 and ends at index 3 ( not including index 3 ).
Python List Methods:
Lists in Python have many built-in methods that you can use to modify or manipulate the list. Here are some of the most commonly used methods:
- append() – It is used to add an element to the end of the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Add an element to the end of the list
my_list.append('date')
# Print the updated list
print(my_list)
- extend() – It is used to add the elements of another list to the end of the list or to combine two lists.
# Define a list
my_list = ['apple', 'banana']
# Extend the list with a tuple
my_list.extend(('cherry', 'date'))
# Extend the list with a set
my_list.extend({'elderberry', 'fig'})
# Print the updated list
print(my_list)
- insert() – It is used to insert an element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Insert an element at index 1
my_list.insert(1, 'date')
# Print the updated list
print(my_list)
4. remove() – It is used to remove the first occurrence of an element from the list.
# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana']
# Remove the first occurrence of 'banana'
my_list.remove('banana')
# Print the updated list
print(my_list)
- pop() – It removes and returns the element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Remove and return the last element
removed_element = my_list.pop()
# Print the updated list and the removed element
print("Updated list:", my_list)
print("Removed element:", removed_element)
6. sort() – It sorts the elements of the list in ascending order.
# Define a list of numbers
my_list = [3, 1, 4, 1, 5, 9, 2, 6]
# Sort the list in descending order
my_list.sort(reverse=True)
# Print the sorted list
print(my_list)
7 .reverse() – It reverses the order of the elements in the list.
# Define a list of strings
my_list = ['apple', 'banana', 'cherry']
# Reverse the list
my_list.reverse()
# Print the reversed list
print(my_list)
- clear() – It is used to remove all elements from a list, effectively emptying the list. After the clear() function is applied to a list, the list becomes empty with a length of 0.
# Define a list of strings
my_list = ['apple', 'banana', 'cherry']
# Clear all elements from the list
my_list.clear()
# Print the cleared list
print(my_list)
- copy() – It creates a shallow copy of a list. The shallow copy means that a new list is created with the same elements as the original list, but the elements themselves are not duplicated. Any changes made to the elements in the copied list will also affect the original list, and vice versa.
# Define a list with immutable elements
my_list = [1, 2, 3]
# Create a shallow copy of the list
my_list_copy = my_list.copy()
# Modify the copied list
my_list_copy.append(4)
# Print both lists
print("Original list:", my_list)
print("Copied list:", my_list_copy)
- index() – It is used to find the index of the first occurrence of a specified element within a list. If the element is not found in the list, it raises a ValueError.
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Find the index of 'banana'
index_of_banana = my_list.index('banana')
# Print the index
print("Index of 'banana':", index_of_banana)
- count() – It is used to count the number of occurrences of a specified element in a list.
# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana', 'apple']
# Count occurrences of 'banana'
banana_count = my_list.count('banana')
# Print the count
print("Count of 'banana':", banana_count)
Updating list values:
Lists in Python are mutable, and their values can be updated by using the slice and assignment the ( = ) operator.
# Define a list
my_list = [1, 2, 3, 4, 5]
# Remove elements at indices 1 to 3
my_list[1:4] = []
# Print the updated list
print(my_list)
Built-in function for Python lists:
Here are some examples of commonly used built-in functions for lists in Python:
- len(): It returns the length of the list.
# Define a list
my_list = [1, 2, 3, 4, 5]
# Get the length of the list
list_length = len(my_list)
# Print the length
print("Length of the list:", list_length)
- max(): It returns the largest element in the list.
# Define a list of numbers
my_list = [1, 5, 3, 9, 2]
# Get the largest element in the list
largest_element = max(my_list)
# Print the largest element
print("Largest element:", largest_element)
- min(): It returns the smallest element in the list.
# Define a list of numbers
my_list = [10, 5, 20, 3, 8]
# Get the smallest element in the list
smallest_element = min(my_list)
# Print the smallest element
print("Smallest element:", smallest_element)
- sum(): It returns the sum of all elements in the list.
# Define a list of numbers
my_list = [1, 2, 3, 4, 5]
# Calculate the sum of the elements in the list
total_sum = sum(my_list)
# Print the total sum
print("Sum of the list:", total_sum)
5. sorted(): It returns a new sorted list.
# Define a list of numbers
my_list = [5, 2, 9, 1, 5, 6]
# Get a new sorted list
sorted_list = sorted(my_list)
# Print the sorted list
print("Sorted list:", sorted_list)
- list(): It converts an iterable to a list.
# Define a tuple
my_tuple = (1, 2, 3, 4)
# Convert the tuple to a list
my_list = list(my_tuple)
# Print the list
print("List from tuple:", my_list)
7. any(): It returns True if at least one element in the list is True.
# Define a list of Boolean values
my_list = [False, False, True, False]
# Check if any element is True
result = any(my_list)
# Print the result
print("Any True in the list:", result)
- all(): It returns True if all elements in the list are True.
# Define a list of Boolean values
my_list = [True, True, True]
# Check if all elements are True
result = all(my_list)
# Print the result
print("All True in the list:", result)
9. enumerate(): It returns an iterator that contains tuples of (index, element) pairs.
# Define a list
my_list = ['apple', 'banana', 'cherry']
# Use enumerate to get index and element
for index, element in enumerate(my_list):
print(f"Index: {index}, Element: {element}")
- zip(): It returns an iterator that aggregates elements from multiple lists into tuples.
# Define two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
# Use zip to combine them into tuples
zipped = zip(list1, list2)
# Convert the zipped object to a list and print
zipped_list = list(zipped)
print(zipped_list)
11.reversed(): It returns a reverse iterator that can be used to iterate over a list in reverse order.
# Define a list
my_list = [1, 2, 3, 4, 5]
# Convert the reversed iterator to a list
reversed_list = list(reversed(my_list))
# Print the reversed list
print(reversed_list)
Iterating over a list
We can use a for loop to iterate over the list elements. Here’s an example:
# Define a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date']
# Use a for loop to iterate over the list
for fruit in fruits:
print(fruit)
Membership operator in list
We can use operator (i.e. in or not in) on list elements. If an element is in list then it returns True. If an element is not in list it return False. Here’s an example:
# Example list
fruits = ['apple', 'banana', 'cherry', 'date']
# Using 'in' to check if an element is in the list
print('apple' in fruits) # Output: True
print('orange' in fruits) # Output: False
# Using 'not in' to check if an element is not in the list
print('grape' not in fruits) # Output: True
print('banana' not in fruits) # Output: False
Repetition on list
We can use (*) operator for repetition of list. Here’s an example:
# Example list
fruits = ['apple', 'banana', 'cherry']
# Using * operator for repetition
repeated_list = fruits * 3
print(repeated_list)
# Output: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry']
Concatenation on list
We can use (+) operator for concatenation of list. Here’s an example:
# Example lists
list1 = ['apple', 'banana']
list2 = ['cherry', 'date']
# Using + operator for concatenation
combined_list = list1 + list2
print(combined_list)
# Output: ['apple', 'banana', 'cherry', 'date']
List Comprehension
List comprehension is a concise and expressive way of creating lists in Python. It allows you to define a list and its elements within a single line of code, combining the functionality of a for loop, optional if conditions, and even nested loops. List comprehensions are preferred for their readability and efficiency compared to traditional for loops.
- Simple For Loop List Comprehension:
This type of list comprehension is used to create a list by iterating over elements from an iterable (e.g., list, tuple, string) without any filtering or conditions. Here’s an example:
# Example list
numbers = [1, 2, 3, 4, 5]
# List comprehension without filtering or conditions
new_list = [num for num in numbers]
print(new_list) # Output: [1, 2, 3, 4, 5]
- Loop and If Condition List Comprehension:
This type of list comprehension includes an if condition to filter elements while iterating over the iterable. Only elements that satisfy the condition are included in the new list. Here’s an example:
# Example list
numbers = [1, 2, 3, 4, 5, 6]
# List comprehension with an if condition
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
- Loop and If-Else Condition List Comprehension:
This type of list comprehension allows you to perform different operations based on the if-else condition while iterating over the iterable. Here’s an example:
# Example list
numbers = [1, 2, 3, 4, 5, 6]
# List comprehension with if-else condition
result = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]
print(result)
# Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
- Nested Loop List Comprehension:
This type of list comprehension allows you to use nested loops for creating more complex lists by iterating over multiple iterables simultaneously. Here’s an example:
# Example nested loops
colors = ['red', 'green', 'blue']
objects = ['ball', 'box', 'pen']
# List comprehension with nested loops
combinations = [f"{color} {obj}" for color in colors for obj in objects]
print(combinations)
# Output: ['red ball', 'red box', 'red pen', 'green ball', 'green box', 'green pen', 'blue ball', 'blue box', 'blue pen']
Shallow Copy and Deep Copy of Lists in Python:
In Python, when dealing with lists or other compound data structures, understanding the concepts of shallow copy and deep copy is crucial. Both concepts involve creating a new copy of an existing list, but they differ in how they handle nested objects within the list.
- Shallow Copy:
A shallow copy of a list creates a new list object but does not create copies of the elements inside the list. Instead, it copies references to the original objects. This means that changes made to nested objects within the copied list will affect the original list, and vice versa. To perform a shallow copy, you can use the `copy()` method or the slicing notation `[:]`. Example of Shallow Copy:
import copy
# Original list with a nested list
original_list = [[1, 2, 3], [4, 5, 6]]
# Shallow copy using the copy() method
shallow_copy1 = original_list.copy()
# Shallow copy using slicing notation
shallow_copy2 = original_list[:]
# Modifying a nested element in the copied list
shallow_copy1[0][0] = 99
print("Original List:", original_list)
# Output: Original List: [[99, 2, 3], [4, 5, 6]]
print("Shallow Copy 1:", shallow_copy1)
# Output: Shallow Copy 1: [[99, 2, 3], [4, 5, 6]]
print("Shallow Copy 2:", shallow_copy2)
# Output: Shallow Copy 2: [[99, 2, 3], [4, 5, 6]]
- Deep Copy:
A deep copy of a list creates a new list object and also recursively creates copies of all the nested objects within the original list. In other words, the copied list and its nested objects are entirely independent of the original list and its nested objects. To perform a deep copy, you need to use the `deepcopy()` function from the `copy` module. Example of Deep Copy:
import copy
# Original list with nested lists
original_list = [[1, 2, 3], [4, 5, 6]]
# Creating a deep copy
deep_copy = copy.deepcopy(original_list)
# Modifying a nested element in the deep copy
deep_copy[0][0] = 99
print("Original List:", original_list)
# Output: Original List: [[1, 2, 3], [4, 5, 6]]
print("Deep Copy:", deep_copy)
# Output: Deep Copy: [[99, 2, 3], [4, 5, 6]]
Shallow copy is faster and suitable when you want to create a new list but share references to nested objects. Deep copy is appropriate when you need an entirely independent copy of the original list and all its nested objects.