Zack
Zack

Reputation: 671

Need for range in a for loop

def sum_items(list1, list2):
    sum_list = []
    for i in range(len(list1)):
        sum_list.append(list1[i] + list2[i])


return sum_list

Why is the range function needed for something like this? Would the result not be the same if we simply used the len of list1?

Upvotes: 1

Views: 245

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121914

Because a for loop in Python is really a for each loop; you need to give it an iterable to loop over; you are not looping for a certain number of iterations, you are iterating over elements, one element after another.

If you were to try to loop over just the length, you'd get an exception:

>>> for i in 42:
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

For your specific example, you don't need to use range() either, I'd use the zip() function instead:

def sum_items(list1, list2):
    sum_list = []
    for i, j in zip(list1, list2)
        sum_list.append(i + j)
    return sum_list

or, combined with a list comprehension:

def sum_items(list1, list2):
    return [i + j for i, j in zip(list1, list2)]

or using sum() to just sum all values in each zipped tuple:

def sum_items(list1, list2):
    return [sum(t) for t in zip(list1, list2)]

zip() takes elements from each of the argument iterables and pairs up the elements, one by one; [1, 2, 3] and ['foo', 'bar', 'baz'] becomes [(1, 'foo'), (2, 'bar'), (3, 'baz')]. More input arguments mean more elements in the output tuples.

Upvotes: 6

Hyperboreus
Hyperboreus

Reputation: 32429

Actually, you don't need neither range nor a for-loop. Your problem is a simple list comprehension:

[sum(t) for t in zip(list1,list2)]

In my personal experience and opinion, in most cases when you see range(len(x)), something is wrong with the design.

Upvotes: 0

Talandar
Talandar

Reputation: 116

Using just the len(list1) for your iterator only gives one value - the length of the list. If you want to iterate over the whole set of values in each list, you need to create a range of all the indexes - using the range() operator.

Upvotes: 0

Related Questions