user11053972
user11053972

Reputation:

question regarding index errors and division

I have two lists and I wanted to create generate the quotients using a for loop. Specifically, I would want to have .5 and .25 and .125 and in that order. Of course, I could just take these values and determine the quotients manually, but I am looking at this from the perspective of someone who is taking their first stab at learning Python. I have read some other articles on for loops, but do not see why the below produces : index error: list index out of range. Thus, I am looking not only for the modification of this code but also a reasonable explanation as to why there is such an error.

x=[2,4,16]
y=[4,16,128]
for i in y:
    y[i]/x

Upvotes: 0

Views: 44

Answers (3)

wleao
wleao

Reputation: 2346

I believe what you need is to zip both lists then apply division over the given iteration values:

x=[2,4,16]
y=[4,16,128]
for xi, yi in zip(x, y):
    print(xi/yi)

That yields:

0.5 0.25 0.125

In order to understand what zip is doing: https://docs.python.org/3.3/library/functions.html#zip

Upvotes: 1

jgoday
jgoday

Reputation: 2836

You are not iterating over the index, you are iterating with the values

for i in y:
   y/x[?]

If you want to iterate with indexes you could do that with enumerate

for index, value in enumerate(y):
    y[index]/x[index]

Upvotes: 0

NoSplitSherlock
NoSplitSherlock

Reputation: 625

Take a look at the following:

x=[2,4,16]
y=[4,16,128]
for i in y:
    print(f"i: {i}")
    print(f"y: {y}")

This is the output:

i: 4
y: [4, 16, 128]
i: 16
y: [4, 16, 128]
i: 128
y: [4, 16, 128]

You are looking for y[4] in the first loop, but it doesn't exist. If you want to loop through the list you can do this:

x=[2,4,16]
y=[4,16,128]
for i in range(len(y)):
    print(f"i: {i}")
    print(y[i])

Output:

i: 0
4
i: 1
16
i: 2
128

Upvotes: 1

Related Questions