+

Python | Operation for each item in the list

Method # 1: Using List Comprehension
This method performs the same task in the background as looping constructs. The advantage of this particular method is that it is one liner and also improves the readability of the code.

# Python3 demo code
# operations with each list item
# using the comprehension list

  
# initializing list

test_list = [ "geeks" , "for" , "geeks" , " is " , " best " ]

  
# print original list

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

 
# operations with each list item
# using the comprehension list
# uppercase each item

res = [i.upper () for i in test_list]

 
# print result

print ( "The uppe rcased list is: " + str (res))

Exit:

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

Method # 2: Using map()
Using the map function, you can easily associate an element with a desired operation. This is the most elegant way to accomplish or solve this kind of problem.

# Python3 demo code
# operations with each list item
# using the map ()

  
# initializing list

test_list = [ "Geeks" , " foR " , " gEEks " , "IS" , "bEST" ]

 
# print original list a

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

 
# operations with each list item
# using map ()
# uppercase each element

res = list ( map ( str . lower, test_list))

 
# print result

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

Exit:

 The original list is: [`Geeks`,` foR`, `gEEks` , `IS`,` bEST`] The uppercased list is: [`geeks`,` for`, `geeks`,` is`, `best`] 
Get Solution for free from DataCamp guru