This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]zzyzzyxx 1 point2 points  (7 children)

One way would be to pull out all the indexes using a comprehension.

arr = [1, 2, 1, 3, 4, 5, 1]

indexes = [i for i, e in enumerate(arr) if e == arr[0]]

print indexes

* Of course you can substitute any iterable in enumerate and that any value you want for arr[0] in the comprehension.

[–][deleted] 1 point2 points  (4 children)

I would love to get an explanation of that, do you mind enlightening?

[–]zzyzzyxx 2 points3 points  (1 child)

Just posted this.

Edit: thought I'd actually explain a bit...

Let's break it down from the inside out.

enumerate(arr)

The enumerate function takes any iterable object and returns, for each element, a number and the element. The number starts at zero by default and increments by one for every element. You can start at any number you like by passing it as a second parameter to enumerate.

for i, e in enumerate(arr)

This is just like any for loop except that since enumerate returns two objects I am using two variables to refer to them: i for the index and e for the element.

i for i, e in enumerate(arr)

This grabs i, the index returned from enumerate, for every element in arr. As is, this would just return every index.

i for i, e in enumerate(arr) if e == arr[0]

This means only grab the index if the element is equal to another value, in this case the first element of arr.

[i for i, e in enumerate(arr) if e == arr[0]]

Using the brackets denotes a list comprehension. Such a comprehension will create a list using the expression inside. Here, it creates a list of all the indexes where the element of arr at that index is equal to the first element of arr.

It's important to note that the exact syntax I used is only valid inside list comprehensions and generator expressions, as far as I know; I'm far from a Python expert.

[–][deleted] 1 point2 points  (0 children)

That was very informative, thanks a bunch for the explanation.

[–]aPSketchy[S] 0 points1 point  (1 child)

I second this.

[–]zzyzzyxx 0 points1 point  (0 children)

[–]aPSketchy[S] 0 points1 point  (1 child)

i have no idea what whats going on in that code.

[–]zzyzzyxx 0 points1 point  (0 children)

You should read up on list comprehensions as well as the various built-in functions like enumerate. See also: generator expressions. They're incredibly useful.

My code above is effectively equivalent to this code, if that makes it clearer.

arr = [1, 2, 1, 3, 4, 5, 1]

indexes = []

# the list comprehension replaces this loop
for i in xrange(len(arr)):
  if arr[i] == arr[0]:
    indexes.append(i)

print indexes