In my code I'm trying to divide all of the second row in the nested list by the variable. This works fine but it asks for the variable for every item on the list instead of just once.
This is the code I have:
nlist = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
def divide():
x = int(input('what is your divider?:'))
return x
nlist[1] = [num / divide() for num in nlist[1]]
print(nlist)
Output:
what is your divider?:5
what is your divider?:5
what is your divider?:5
what is your divider?:5
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]]
What I want the output to be:
what is your divider?:5
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]]
nlist[1] = [num / divide() for num in nlist[1]]
divide()
is called each time. Use
divide_value = divide()
nlist[1] = [num / divide_value for num in nlist[1]]
to call it once only and store it.