Open In App

Python | Operation to each element in list

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, we always come across situations in which we require to apply certain function to each element in a list. This can be easily done by applying a loop and performing an operation to each element. But having shorthands to solve this problem is always beneficial and helps to focus more on important aspects of problem. Let’s discuss certain ways in which each element of list can be operated. 

Method #1: Using list comprehension

This method performs the same task in the background as done by the looping constructs. The advantage this particular method provides is that this is a one-liner and also improves code readability. 

Python3
# Python3 code to demonstrate
# operations on each list element
# using list comprehension

# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]

# printing original list
print("The original list is : " + str(test_list))

# operations on each list element
# using list comprehension
# uppercasing each element
res = [i.upper() for i in test_list]

# printing result
print("The uppercased list is : " + str(res))

Output
The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
The uppercased list is : ['GEEKS', 'FOR', 'GEEKS', 'IS', 'BEST']

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #2: Using map()

Using map function, one can easily associate an element with the operation one wishes to perform. This is the most elegant way to perform or solve this kind of problems. 

Python3
# Python3 code to demonstrate
# operations on each list element
# using map()

# initializing list
test_list = ["Geeks", "foR", "gEEks", "IS", "bEST"]

# printing original list
print("The original list is : " + str(test_list))

# operations on each list element
# using map()
# lowercasing each element
res = list(map(str.lower, test_list))

# printing result
print("The lowercased list is : " + str(res))

Output
The original list is : ['Geeks', 'foR', 'gEEks', 'IS', 'bEST']
The lowercased list is : ['geeks', 'for', 'geeks', 'is', 'best']

Method #3: Using enumerate and iteration

Another approach that can be used to perform operations on each element in a list is to use the for loop in conjunction with the enumerate() function. The enumerate() function returns an iterator that produces tuples containing the index and value of each element in the list.

Here is an example of using enumerate() and a for loop to convert each element in a list to uppercase:

Python3
# initializing list
test_list = ["geeks", "for", "geeks", "is", "best"]

# printing original list
print("The original list is:", test_list)

# using enumerate() and a for loop to uppercase each element
for i, element in enumerate(test_list):
    test_list[i] = element.upper()

# printing result
print("The uppercased list is:", test_list)

Output
The original list is: ['geeks', 'for', 'geeks', 'is', 'best']
The uppercased list is: ['GEEKS', 'FOR', 'GEEKS', 'IS', 'BEST']

The time complexity of the approach using enumerate() and a for loop to perform an operation on each element in a list is O(n), where n is the number of elements in the list. This is because the loop will iterate over all n elements in the list and perform the operation on each element.

The space complexity of this approach is also O(n), as the original list is modified in-place and no additional space is required to store the result. The modified list will take up the same amount of space as the original list.


Previous Article
Next Article

Similar Reads

Python | Perform operation on each key dictionary
Sometimes, while working with dictionaries, we might come across a problem in which we require to perform a particular operation on each value of keys. This type of problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is the naive method in which this task can be pe
4 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Sorting List of Lists with First Element of Each Sub-List in Python
In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list of lists by the first element of each sub-list. Thi
3 min read
Python - Binary operation on specific keys in Dictionary List
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform certain operations over some keys in the dictionary throughout the list and return the result. This kind of problem is common in domains involving data like web development. Let's discuss certain ways in which this task can be performed. Input : tes
6 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Python Program to find the cube of each list element
Given a list, the task is to write a python program to cube all the list elements. Input: [1, 2, 3, 4] Output: [1, 8, 27, 64] Explanation: Cubing all the list elementsInput: [2, 4, 6] Output: [8, 64, 216] Method 1: Using loop This is the brute force way. In this, we just multiply the same element two times by itself. Example: C/C++ Code # Initializ
4 min read
Python | Find most common element in each column in a 2D list
Given a 2D list, write a Python program to find the most common element in each column of the 2D list. Examples: Input : [[1, 1, 3], [2, 3, 3], [3, 2, 2], [2, 1, 3]] Output : [2, 1, 3] Input : [['y', 'y'], ['y', 'x'], ['x', 'x']] Output : ['y', 'x'] Method #1 : Using most_common() from collections module most_common() return a list of the n most co
5 min read
Python | Adding K to each element in a list of integers
While working with the Python lists, we can come over a situation in which we require to add the integer k to each element in the list. We possibly need to iterate and add k to each element but that would increase the line of code. Let's discuss certain shorthands to perform this task. Method #1: Using List Comprehension List comprehension is just
5 min read
Python | Repeat each element K times in list
Many times we have this particular use case in which we need to repeat each element of the list K times. The problems of making a double clone have been discussed but this problem extends to allow a flexible variable to define the number of times the element has to be repeated. Let's discuss certain ways in which this can be performed. Approach 1:
7 min read
Python | Reverse sign of each element in given list
Given a list of integers, write a Python program to reverse the sign of each element in given list. Examples: Input : [-1, 2, 3, -4, 5, -6, -7] Output : [1, -2, -3, 4, -5, 6, 7] Input : [-5, 9, -23, -2, 7] Output : [5, -9, 23, 2, -7] Methods #1: List comprehension C/C++ Code # Python3 program to Convert positive # list integers to negative and vice
3 min read