0

I want to get even indexed numbers from the python list here is my code snippet:

for i in array:
        if array.index(i) % 2 == 0:
            print(str(i) + " >> index: " + str(array.index(i)))

The list I am providing is as below:

-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41

But in output its not showing me the number 84 having index 16 even is it divisible by 2

Why is it omitting the index 16 also sometimes I'm getting odd index and even indexes both!

jdk
  • 451
  • 1
  • 6
  • 18
  • 1
    What are the values in your array? `array.index` finds the *first* index with that value. That's not necessarily your current index. – deceze Aug 14 '20 at 06:11
  • ```-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41``` these are values in the list i understand the what you said – jdk Aug 14 '20 at 06:14

4 Answers4

3

If your values aren't unique, array.index may find the index for a different value than your current one. You should use enumerate for explicit indexes:

for i, value in enumerate(array):
    if i % 2 == 0:
        ...

But list slicing can already do exactly that without the extra check:

for i in array[::2]:
    print(i)
deceze
  • 510,633
  • 85
  • 743
  • 889
  • in slicing it shows the first index of 84 which is 9, but using enumerate solved the problem. Thank you. – jdk Aug 14 '20 at 06:23
1

As you have twice 84, array.index(84) returns 9 for both of them, to get only even items you may use enumerate like

for idx, value in enumerate(array):
    if idx % 2 == 0:
        print(value, ">> index:", idx)
azro
  • 53,056
  • 7
  • 34
  • 70
1

array.index(i) is the index of the first occurrence of i. If you're processing a duplicate element of the list, this will return the earlier index, not the current index.

For instance, 84 is at index 9 and 16. When you get to index 16, array.index(i) returns 9, which isn't even, so nothing is printed.

You can use enumerate() to get the indexes along with the elements, and test that.

for i, el in enumerate(array):
    if i % 2 == 0:
        print(str(el) + " >> index: " + str(i))
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

As the above answers explained it -

You are doing indexing the wrong way. I will show you how you can do it easily.

odd_i = [] 
even_i = [] 
for i in range(0, len(test_list)): 
    if i % 2: 
        even_i.append(test_list[i]) 
    else : 
        odd_i.append(test_list[i]) 
  
res = odd_i + even_i 

even_i will contain even indices and odd_i will contain odd indices. You can achieve this by slicing too.

Innomight
  • 556
  • 3
  • 15