Page Contents
Python List
Python, a versatile and powerful programming language, offers a variety of data structures to cater to various programming needs. Among these, the Python list stands out as one of the most fundamental and versatile structures. A list in Python is a collection of items, ordered and mutable, capable of holding elements of different data types within square brackets [ ]
. This post delves into the intricacies, functionalities, and applications of Python lists.
Structure and Characteristics
Lists in Python exhibit several key characteristics that make them indispensable in programming.
Firstly, lists are ordered, meaning the elements within a list maintain their position, allowing for sequential access based on their indices.
Secondly, lists are mutable, enabling dynamic modifications such as addition, removal, or modification of elements.
Thirdly, lists can store heterogeneous data types, enabling the creation of complex data structures within a single list. These characteristics make lists highly flexible and adaptable to diverse programming tasks.
Here’s an example of a Python list:
list_days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]
This list contains strings. You can access elements of a list using their index, which starts from 0. For example:
# Printing first element. Index starts from 0. print(list_days[0]) # Printing last element. Negative index starts from -1, which is also the last element. print(list_days[-1]) # Output Sunday Saturday
Reading items in Python List
Reading items in a Python list is a fundamental operation and can be done in several ways, typically involving iteration or direct access through indexing. Here are some common methods for reading items from a Python list:
- Using Indexing: You can access individual items by their index using square brackets
[]
:
my_list = [1, 2, 3, 4, 5] print(my_list[0]) # Output: 1 print(my_list[2]) # Output: 3
You can also use negative indices to access items from the end of the list:
print(my_list[-1]) # Output: 5
2. Using a For Loop: You can iterate over each item in the list using a for
loop:
my_list = [1, 2, 3, 4, 5] for item in my_list: print(item) # Output 1 2 3 4 5
- Using List Slicing: You can read a sublist of items using slicing notation:
my_list = [1, 2, 3, 4, 5] print(my_list[1:3]) # This will print items from index 1 (inclusive) to index 3 (exclusive). # Output [2, 3] list_days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"] print(list_days[1:6]) # 1 is inclusive, 6 is exclusive. print(list_days[:6]) print(list_days[1:]) print(list_days[-4:-1]) # Output ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] ['Wednesday', 'Thursday', 'Friday']
- Using List Comprehensions: List comprehensions provide a concise way to read items from a list while performing some operation.
my_list = [1, 2, 3, 4, 5] squared_list = [x ** 2 for x in my_list] print(squared_list) # Output: [1, 4, 9, 16, 25]
In this example, each item in my_list
is squared and stored in squared_list
.
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Here is another example .
Based on a list of fruits, you want a new list, containing only the fruits that contains character “a”. Without list comprehension you will have to write a for statement with a conditional test inside.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"] print("Old List: ",fruits) new_list = [] for fruit in fruits: if "a" in fruit: new_list.append(fruit) print("New List with For loop: ",new_list) # Output Old List: ['apple', 'banana', 'cherry', 'kiwi', 'mango'] New List with For loop: ['apple', 'banana', 'mango']
The same code with shorter syntax using List Comprehension
new_list1 = [fruit for fruit in fruits if "a" in fruit ] print("New list with list comprehension: ",new_list1) # Output New list with list comprehension: ['apple', 'banana', 'mango']
- Using Built-in Functions: Python provides built-in functions like
map()
andfilter()
to apply a function to each item in a list or to filter items based on a condition. Here is an example.
my_list = [1, 2, 3, 4, 5] squared_list = list(map(lambda x: x ** 2, my_list)) print(squared_list) # Output [1, 4, 9, 16, 25] even_numbers = list(filter(lambda x: x % 2 == 0, my_list)) print(even_numbers) # Output [2, 4]
These methods offer various ways to read items from a Python list, catering to different requirements and programming styles.
Adding items in python list
Adding items to a Python list can be done using various methods, depending on the specific requirements and preferences. Here are some common ways to add items to a list:
- Using
append()
: Theappend()
method adds an item to the end of the list.
my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output [1, 2, 3, 4]
2. Using insert()
: The insert()
method adds an item at a specified index in the list.
my_list = [1, 2, 3] my_list.insert(1, 100) # Insert 5 at index 1 print(my_list) # Output: [1, 100, 2, 3]
3. Using Concatenation: You can use the concatenation operator +
to concatenate two lists, effectively adding the elements of one list to another.
my_list = [1, 2, 3] new_items = [4, 5] my_list += new_items print(my_list) # Output: [1, 2, 3, 4, 5]
4. Using List Concatenation: Similar to the previous method, you can use list concatenation with the extend()
method.
my_list = [1, 2, 3] new_items = [4, 5] my_list.extend(new_items) print(my_list) # Output [1, 2, 3, 4, 5]
5. Using +=
Assignment Operator: You can use the +=
assignment operator to add elements to an existing list.
my_list = [1, 2, 3] my_list += [4, 5] print(my_list) # Output [1, 2, 3, 4, 5]
Changing elements value in python list
To change the value of an element in a Python list, you can simply access the element by its index and assign a new value to it. Python lists are mutable, meaning their elements can be modified. Here’s how you can change the value of an element in a list.
my_list = [1, 2, 3, 4, 5] print("Original list:", my_list) # Change the value of the element at index 3 my_list[3] = 100 print("Modified list:", my_list) # Output Original list: [1, 2, 3, 4, 5] Modified list: [1, 2, 3, 100, 5]
In the above example, we change the value of the element at index 3 from 4
to 100
. Lists in Python are zero-indexed, so the first element has an index of 0
, the second element has an index of 1
, and so on.
You can also use negative indices to access elements from the end of the list. For example, -1
refers to the last element, -2
refers to the second-to-last element, and so forth:
my_list = [1, 2, 3, 4, 5] print("Original list:", my_list) # Change the value of the second last element. my_list[-2] = 100 print("Modified list:", my_list) # Output Original list: [1, 2, 3, 4, 5] Modified list: [1, 2, 3, 100, 5]
Change a range of item values
To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values.
my_list = ["Apple","Banana","Orange","Mango"] print("Original list:", my_list) # Change values of elements from index 2 to 4 my_list[2:4] = ["Pineapple","Kiwi"] print("Modified list:", my_list) # Output Original list: ['Apple', 'Banana', 'Orange', 'Mango'] Modified list: ['Apple', 'Banana', 'Pineapple', 'Kiwi']
If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.
my_list = ["Apple","Banana","Orange","Mango"] print("Original list:", my_list) my_list[1:3] = ["Pineapple","Kiwi","Grapes"] print("Modified list:", my_list) # Output Original list: ['Apple', 'Banana', 'Orange', 'Mango'] Modified list: ['Apple', 'Pineapple', 'Kiwi', 'Grapes', 'Mango']
If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.
my_list = ["Apple","Banana","Orange","Mango"] print("Original list:", my_list) my_list[1:3] = ["Pineapple"] print("Modified list:", my_list) # Output Original list: ['Apple', 'Banana', 'Orange', 'Mango'] Modified list: ['Apple', 'Pineapple', 'Mango']
Removing items from python list
In Python, you can remove items from a list using various methods depending on your requirements. Here are some common methods for removing items from a Python list:
- Using
remove()
: Theremove()
method removes the first occurrence of a specified value from the list.
my_list = [1, 2, 3, 4, 5, 3] my_list.remove(3) print(my_list) # Output [1, 2, 4, 5, 3]
2. Using pop()
: The pop()
method removes an item at a specified index (or the last item if no index is specified) and returns its value.
my_list = [1, 2, 3, 4, 5] removed_item = my_list.pop(2) print("Removed item:", removed_item) print("Updated list:", my_list) # Output Removed item: 3 Updated list: [1, 2, 4, 5]
3. Using del
statement: The del
statement removes an item at a specified index or a slice of items from the list.
my_list = [1, 2, 3, 4, 5] del my_list[2] # Remove index 2. print(my_list) # Output: [1, 2, 4, 5] # Deleting a slice of items del my_list[1:3] print(my_list) # Output: [1, 4, 5]
Loop through python List
- Using for loop: To loop over a Python list, you can use a
for
loop. Here’s a simple example:
my_list = [1, 2, 3, 4, 5] for item in my_list: print(item) # Output 1 2 3 4 5
This will iterate over each item in the list and print it. You can replace print(item)
with whatever operation you want to perform on each item in the list.
We can also loop a python list through index number. Here is an example
list_days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"] print("Print through Index number") for i in range(len(list_days)): print(list_days[i]) # Output Print through Index number Sunday Monday Tuesday Wednesday Thursday Friday Saturday
2. Using While loop: While loops can also be used to iterate over a list in Python. Here’s how you can do it:
my_list = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"] index = 0 print("Print through While loop.") while index < len(my_list): print(my_list[index]) index += 1 # Output Print through While loop. Sunday Monday Tuesday Wednesday Thursday Friday Saturday
This code snippet achieves the same result as the earlier example using a for loop. It iterates over each element in the list and prints it. The index
variable is used to keep track of the current position in the list, and the loop continues as long as index
is less than the length of the list.
While loops can be useful in scenarios where you need more control over the iteration process, such as when you’re iterating based on certain conditions or need to manipulate the index manually. However, in most cases, for loops are simpler and more straightforward for iterating over lists.
Below are some basic looping examples in python.
Summing the elements of a list:
my_list = [1, 2, 3, 4, 5] total = 0 for num in my_list: total += num print("Sum of elements:", total) # Output Sum of elements: 15
Finding the maximum element in a list:
my_list = [1, 5, 2, 8, 3] max_value = my_list[0] for num in my_list: if num > max_value: max_value = num print("Maximum element:", max_value) # Output Maximum element: 8
Counting occurrences of a specific value in a list:
my_list = [1, 2, 2, 3, 4, 2, 5] value_to_count = 2 count = 0 for num in my_list: if num == value_to_count: count += 1 print("Occurrences of", value_to_count, ":", count) # Output Occurrences of 2 : 3
Using the index of each element in the list:
my_list = ['a', 'b', 'c', 'd'] for index, item in enumerate(my_list): print("Index:", index, "Item:", item) # Output Index: 0 Item: a Index: 1 Item: b Index: 2 Item: c Index: 3 Item: d
Looping in reverse:
my_list = ['a', 'b', 'c', 'd'] for item in reversed(my_list): print(item) # Output d c b a
Looping through list comprehension:
my_list = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"] print("Looping through List Comprehension.") [ print(day) for day in my_list] # Output Looping through List Comprehension. Sunday Monday Tuesday Wednesday Thursday Friday Saturday
List Comprehension in Python
Python list comprehensions provide a concise way to create lists. They are a syntactic construct that allows for creating a new list by applying an expression to each item in an existing iterable (such as a list, tuple, or range). List comprehensions are often more readable and compact compared to traditional looping techniques. Here’s an example:
Let’s say we want to create a list containing the squares of the numbers from 1 to 5 using a list comprehension:
cubes= [x**3 for x in range(1, 6)] print(squares) # Output [1, 8, 27, 64, 125]
In this example:
range(1, 6)
generates the numbers 1 through 5.x**3
is the expression that calculates the cube of each number.for x in range(1, 6)
is the iteration part, wherex
takes each value from the range.
The syntax of a list comprehension is [expression for item in iterable]
. You can also add conditions to filter items. For example, if we only want to include even numbers:
even = [x for x in range(1, 6) if x % 2 == 0] print(even) # Output [2, 4]
Here, if x % 2 == 0
filters out the odd numbers.
List comprehensions can be very powerful and concise, but readability should always be a priority. Avoid making them too complex; otherwise, they might become difficult to understand.
Sorting Python List
Sorting a Python list can be done using the sorted()
function or by using the sort()
method of the list object. Here’s how you can do it:
- Using the
sorted()
function:
my_list = [100,23,82,2,1,3,99,18,6] sorted_list = sorted(my_list) print(sorted_list) # Output [1, 2, 3, 6, 18, 23, 82, 99, 100]
2. Using the sort()
method:
my_list = [100,23,82,2,1,3,99,18,6] my_list.sort() print(my_list) # Output [1, 2, 3, 6, 18, 23, 82, 99, 100]
The difference between sorted()
and sort()
is that sorted()
returns a new sorted list without modifying the original list, while sort()
sorts the list in place.
You can also sort lists of strings or custom objects. For example, sorting a list of strings:
my_list = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"] sorted_list = sorted(my_list) print(sorted_list) # Output ['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday']
Similarly, for descending order, you can use the reverse
parameter:
my_list = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"] sorted_list = sorted(my_list, reverse=True) print(sorted_list) # Output ['Wednesday', 'Tuesday', 'Thursday', 'Sunday', 'Saturday', 'Monday', 'Friday']
This will sort the list in descending order.
Customizing Sort function in python
You can customize the sorting order in Python using the key
parameter in the sorted()
function or the sort()
method. This allows you to define a function that calculates a custom sorting key for each element in the list. Here’s how you can do it:
Let’s say you have a list of tuples representing people with their ages, and you want to sort them based on their ages.
You can use the sorted()
function with a custom key function to sort the list based on the second element (age) of each tuple:
people = [('Prakash', 30), ('Shivaay', 5), ('Vikas', 25), ('John', 20)] sorted_people = sorted(people, key= lambda x:x[1]) print("Customize sorting on list of tuples. ") print(sorted_people) # Output [('Shivaay', 5), ('John', 20), ('Vikas', 25), ('Prakash', 30)]
In this example, lambda x: x[1]
defines a function that takes a tuple x
and returns its second element, i.e., the age. So, the list is sorted based on the ages.
You can also use a regular function instead of a lambda function:
def sort_age(person): return person[1] people = [('Prakash', 30), ('Shivaay', 5), ('Vikas', 25), ('John', 20)] sorted_people = sorted(people, key= sort_age) print(sorted_people) # Output [('Shivaay', 5), ('John', 20), ('Vikas', 25), ('Prakash', 30)]
Similarly, you can use the key
parameter with the sort()
method for in-place sorting:
people = [('Prakash', 30), ('Shivaay', 5), ('Vikas', 25), ('John', 20)] people.sort(key = lambda x:x[1]) print(people) # Output [('Shivaay', 5), ('John', 20), ('Vikas', 25), ('Prakash', 30)]
Copy list in python
To copy a Python list, you have a few different options. Here are some common methods:
- Using the
copy()
method or slicing: This creates a shallow copy of the list. Changes made to the copied list won’t affect the original list, but changes to mutable objects within the list (like lists or dictionaries) may affect both lists if they are shallow copies.
original_list = ["Sunday","Monday","Tuesday"] # Using copy() method copied_list_copy = original_list.copy() # Using slicing copied_list_slicing = original_list[:] print("original_list", original_list) print("copied_list with copy method", copied_list_copy) print("copied_list with slicing", copied_list_slicing) # Output original_list ['Sunday', 'Monday', 'Tuesday'] copied_list with copy method ['Sunday', 'Monday', 'Tuesday'] copied_list with slicing ['Sunday', 'Monday', 'Tuesday']
2. Using the list()
constructor: This also creates a shallow copy of the list.
copied_list = list(original_list)
3. Using copy.deepcopy()
from the copy
module: This creates a deep copy of the list, meaning it recursively copies all items within the list. This method is necessary if your list contains nested mutable objects and you want to ensure that changes to them in one list don’t affect the other.
original_list = ["Sunday","Monday","Tuesday",["Wednesday", "Thursday","Friday","Saturday"]] deep_copied_list = copy.deepcopy(original_list) print("deep_copied_list", deep_copied_list) # Output deep_copied_list [1, [2, 3], 4, 5]
Choose the appropriate method based on whether you need a shallow or deep copy and whether your list contains nested mutable objects. For most cases, a shallow copy using the copy()
method or slicing is sufficient.
Join list in Python
To join the elements of a list into a single string in Python, you can use the join()
method. This method concatenates each element of the list with a specified separator between them. Here’s how you can do it:
my_list = ["Sunday","Monday","Tuesday"] joined_list = ", ".join(my_list) print("joined_list: ", joined_list) # Output joined_list: Sunday, Monday, Tuesday
In this example, the join()
method is called on the separator ", "
, and it joins each element of the list with that separator.
You can use any separator you want. For example, to join the elements with a hyphen:
joined_list = "-".join(my_list) print("joined_list: ", joined_list) # Output joined_list: Sunday-Monday-Tuesday
We can join two list using + operator.
my_list1 = ["Sunday","Monday","Tuesday"] my_list2 = ["Wednesday", "Thursday","Friday","Saturday"] joined_list = my_list1 + my_list2 print("joined_list: ", joined_list) # Output joined_list: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
Another way to join two lists is by appending all the items from list2 into list1, one by one:
my_list1 = ["Sunday","Monday","Tuesday"] my_list2 = ["Wednesday", "Thursday","Friday","Saturday"] for day in my_list2: my_list1.append(day) print("joined_list: ", joined_list) # Output joined_list: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
you can use the extend()
method
my_list1 = ["Sunday","Monday","Tuesday"] my_list2 = ["Wednesday", "Thursday","Friday","Saturday"] my_list1.extend(my_list2) print("joined_list: ", my_list1) # Output joined_list: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']