13. When to use Method 1 or Method 2?


#1



https://www.codecademy.com/en/courses/python-beginner-nzzVa/3/2?curriculum_id=4f89dab3d788890003000096


Hello,
I've worked my way through the Python course but I"m running into difficulty of knowing when to use Method 1 or Method 2 for iterating over a list inside a function. It seems that often both ways will work and method 1 appears simpler, but there are times that method 1 does not work and you have to iterate through indexes (described as method 2). Is there a rule to follow to know when and where to use each?

Here is my example code for the linked to lesson:

Method 2 is shown at the top in the function: double_list(x)
Method 1 is shown below in the function: double_list_2(x)

Both produce identical results and I'm struggling to figure out when one is desired or required over the other.

Thank you,

Darren


#2

The most explicit form is easier to read and understand. The second example is elegant, but not entirely descriptive. It is not obvious that the list is being modified. For this reason, I like the first example. It is explicit.

Time for an admission... I've been guilty of stating that an iterable cannot be mutated when using an item loop. (item in object). Obviously I've been wrong all along. I think this comes from my penchant for using index in range to mutate a list, and item in object to lookup items and values in the object.


#3

Thanks very much for your response! Your explanation definitely helps.

Out of curiosity... is it possibly to iterate inside a function that takes two arguments?


#4

Yes. Most often we will write loops into functions to make them reusable. Loops in global scope get run once and that's usually it (unless they themselves are inside a loop, such as a game with an infinite outer loop).

def function(*args):
    a, b, c = args
    for i in range(a,b,c):

Let's assume this function takes three arguments (* => splat, for multiple args in one parameter). The above unpacks the splat into the three local variables. In the range they are the start, stop and step values respectively. Just as an example.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.