You can apply an operation to lists and other sequences for each item and collect the results.
The following code shows how to update all the counters in a list can be done easily with a for loop:
counters = [1, 2, 3, 4] updated = [] # ww w.ja va 2 s. c o m for x in counters: updated.append(x + 10) # Add 10 to each item print( updated )
Python provides built-ins that do most of the work.
The map function applies a function to each item in an iterable object and returns a list containing all the function call results.
For example:
counters = [1, 2, 3, 4] def inc(x): return x + 10 # Function to be run # from w w w .ja v a 2s . c o m d=list(map(inc, counters)) # Collect results print( d )
Here, we map inc method on each list item and collects all the return values into a new list.