IDEs & Debugging

There are a number of way to fix double_lists. I'll show a few here. First, the original code:

lists.py
def double_list(l):
    new_list = l
    for i in range(len(new_list)):
        new_list[i] *= 2
    return new_list

Sometimes you want your fix to change as little code as possible to make it easier to understand. Keeping the spirit of the original code, line 2 was supposed to be making a copy of l into new_list but accidentally aliased it instead. To actually do a copy we can use copy.copy:

lists.py
import copy


def double_list(l):
    new_list = copy.copy(l)
    for i in range(len(new_list)):
        new_list[i] *= 2
    return new_list

It is good style to avoid modifying data more than necessary. Instead of filling the new list with old data before doubling each in turn, we can instead make an empty list and fill it as we go. This code is shorter and more expressive of our actual task:

lists.py
def double_list(l):
    new_list = []
    for i in l:
        new_list.append(i * 2)
    return new_list

Finally, the functional approach is to avoid mutating any data at all. Instead we can generate the new values at the same time as creating the new list. Using a list comprehension allows us to do this on one line:

lists.py
def double_list(l):
    return [i * 2 for i in l]