Har
Har

Reputation: 3918

Python 2.7: How to use avoid multiple iterations of a loop

I have the following list which say I want to process somehow and then print out the elements:

mylist = [1,2,3,4,5,6]
def increment_list(l, amount):
    return [x + amount for x in l]

def print_incremented_list(l):
    for item in l:
        print(item)

l = increment_list(mylist, 1)
print_incremented_list(l)

one other way to write this would be

print_incremented_list(increment_list(mylist, 1))

The issue I have with the one above is that the function calls are nested within each other which adds a bit of complexity. I find it easier to read when they are put on separate lines but that may be my preference.

The main problem is that both approaches suffer from having to go through the list twice, is there a way to avoid this without having to nest all the functionality inside a single function such as

def increment_list(l, amount):
    incremented_list = []
    for a in l:
        incremented_list.append(a+amount)
        print(a+amount)
    return incremented_list

Upvotes: 0

Views: 81

Answers (1)

Amadan
Amadan

Reputation: 198324

You can avoid going through the list twice by using a generator instead of a list (note the round brackets instead of the square ones):

def increment_list(l, amount):
    return (x + amount for amount in l)

With that, the functionality is cleanly separated, but only one pass through the list will be done.

Upvotes: 3

Related Questions