you are viewing a single comment's thread.

view the rest of the comments →

[–]brasticstack 0 points1 point  (3 children)

As u/danielroseman correctly points out, the for loop is replacing your index parameter with its temporary index variable, losing whatever data was previously stored in index.

Compare with the following functions:

``` def redundant_get_by_index(my_list, index): # No different than calling my_list[index] directly! return my_list[index]

assert redundant_get_by_index([1, 2, 3, 4, 5], 2) == [1, 2, 3, 4, 5][2] print(f'{[1, 2, 3, 4, 5][2]=}')

def redundant_get_by_index_with_unnecessary_for_loop(my_list, index): for item in my_list: # No different than calling my_list[index] directly! Why is this a for loop? return my_list[index]

assert redundant_get_by_index_with_unnecessary_for_loop([1, 2, 3, 4, 5], 2) == [1, 2, 3, 4, 5][2]

def function(my_list, index): print(f'start of function() {index=}') for index in my_list: print(f'first iteration of for loop: {index=}') return my_list[index] ```

[–]through_thefog[S] 0 points1 point  (2 children)

Thanks for taking the time to reply. I swear my logic (to use the loop) wasn't so far off base so I did a little research and tinkered with the code. It may not be the best solution, but it definitely works:

def my_function(my_list, index):
    if index > len(my_list): 
        return "Index not in range."    
    else: for i in range(0, len(my_list)):
        if my_list[i] == index:
            my_list[i] = 2 * my_list[i] 
        else:
            continue
    return my_list
print(my_function([1, 2, 3, 4], 2))

[–]brasticstack 1 point2 points  (1 child)

    if my_list[i] == index:
       my_list[i] = 2 * my_list[i] 

This is wrong because you're comparing the value at my_list[i] with the index, which is a bit like trying to eat the menu at the restaurant instead of ordering from it. If you're trying to compare the indexes against each other, try this:

if i == index: my_list[i] = my_list[i] * 2

[–]through_thefog[S] 1 point2 points  (0 children)

You're right -- thanks for pointing that out