0
nums = [11, 2,4, 2, 5]
for i in nums:
    print(nums.index(i),i )

I run the above code and it uses same index for similar elements(here 2 at index 1 and 3). I wasn't aware of this python list behavior, does it mean the use of lists can be restrictive for similar elements in same list?

jtp
  • 67
  • 5
  • 1
    Have you checked the [documentation](https://docs.python.org/3.8/tutorial/datastructures.html#more-on-lists) for the method? The `index` method returns *the first item whose value is equal to* the argument. – Ted Klein Bergman Mar 14 '21 at 01:44
  • it sure does, thank you!! – jtp Mar 15 '21 at 03:18

1 Answers1

1

The index() method returns the position at the first occurrence of the specified value. So it returns first index of number 2.

nums = [11, 2,4, 2, 5]

You can enumerate() to get all indexes.

nums = [11, 2,4, 2, 5]
for i,n in enumerate(nums):
    print(i, n)


0 11
1 2
2 4
3 2
4 5
Rima
  • 1,447
  • 1
  • 6
  • 12