Reddy
Reddy

Reputation: 15

Unable to understand why this Python FOR loop isn't working as intended

I'm trying to generate a random dataset to plot a graph in Python 2.7.

In which the 'y' list stores 14 integers between 100 and 135. I did that using the following code:

y = [random.randint(100, 135) for i in xrange(14)]

And for the 'x' list, I wanted to store the index values of the elements in 'y'. To achieve this, I tried using the code:

x = []

for i in y:

   pt = y.index(i)

   x.append(pt)

But when I run this, the result of the for loop ends up being:

x = [0, 1, 1, 3, 4, 5, 6, 3, 1, 9, 1, 11, 12, 13]

Why isn't the result the following?

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Upvotes: 0

Views: 73

Answers (2)

Erica
Erica

Reputation: 2477

Python is returning the first location of a value in y.

Running your code, here's an example y:

[127, 124, 105, 119, 121, 118, 130, 123, 122, 105, 110, 109, 108, 110]

110 is at both 10 and 13. 105 is at both 2 and 9. Python stops looking after it finds the first one, so x then becomes:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 2, 10, 11, 12, 10]

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49330

list.index() finds the index of the first occurrence of that object in the list, which produces the results you saw when the list has repeated elements. Something like [1, 1, 1].index(1) would produce 0.

If you want to generate a list of indices, you can use list(range(len(y))), which finds the length of y, creates a range() object out of it, then creates a list out of that object. Since you're using Python 2, you can omit the list() call, since Python 2's range() will already return a list.

Upvotes: 0

Related Questions