'Why does a Python list not have unique indices for contiguous duplicate elements?
I was storing a list with elements
[0, 1, 2, 3, 4, 4]
When I iterated through it and printed each element's index, my output was something like this:
0
1
2
3
4
4
I just thought if it was printing just the elements so I tried one more input
[1,2,3,4,5,6,7]
and this time I got proper indexes like
0
1
2
3
4
5
6
Why happened in the first case and how can I solve this?
n=input()
l=list(input().split())
print(l)
for i in l:
print(l.index(i))
Expected Output:
0
1
2
3
4
5
Actual Output:
0
1
2
3
4
4
Solution 1:[1]
The .index
function doesn't work as you expected.
.index()
doesn't return the index of the item in the array, it returns you the first index or location of the value (see this).
In your code
l = [0, 1, 2, 3, 4, 4]
for i in l:
print(l.index(i)) #i is the value itself
What's actually happening is that each time it's searching for the first occurrence of the value i
. In the list l = [0, 1, 2, 3, 4, 4]
, when you reach the last 4, you actually ask Python to give you the "first occurrence of 4
in the list l
", so Python gives you the "index" 4.
In JavaScript, it'll be the equivalent of array.indexOf(val)
.
What you seem to be looking for is the enumerate function:
for ind, val in enumerate(l):
...
Solution 2:[2]
Use enumerate()
if you would like to get the position of the elements in the list.
Or, if you just want to print the values:
for i in l:
print(i)
Documentation:
https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20index
list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
https://docs.python.org/3/library/functions.html#enumerate
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
Solution 3:[3]
list_name.index(i)
returns the index of the first occurrence that element.
So, if your list was:
[1,2,3,4,5,6,5]
And you printed out l.index(i)
by iterating over the list, the output would be.
0
1
2
3
4
5
4
Because 5 has the first occurrence at position 4 in the list.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gino Mempin |
Solution 2 | Gino Mempin |
Solution 3 | Gino Mempin |