2

I just want to get those with the index that is a multiple of two

    code=[1,2,4,7,2,6,8]
    ncode=[code[i] for i%2==0]
gaganso
  • 2,914
  • 2
  • 26
  • 43
  • Possible duplicate of [Explain Python's slice notation](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) – gaganso Jul 04 '16 at 17:14

3 Answers3

4

Just use this indexing method:

code[::2]

If you want the odd index

code[1::2]

Generally, this is how it works:

seq = L[start:stop:step]

seq = L[::2] # get every other item, starting with the first
seq = L[1::2] # get every other item, starting with the second
MaThMaX
  • 1,995
  • 1
  • 12
  • 23
  • mathmax, this is great. I just read about 'step' in list slicing. Can you please provide more information so that OP understands this and if he finds it better he might accept this. – gaganso Jun 02 '16 at 15:25
1

You can use list comprehensions this way :

code=[1,2,4,7,2,6,8]
print [val for i,val in enumerate(code) if i%2==0]

enumerate() returns the index and value at the index, which is stored in i and value respectively.

For more details:

list comprehension

enumerate

gaganso
  • 2,914
  • 2
  • 26
  • 43
0
code = [1,2,4,7,2,6,8]
new_code = []

for i in range(0, len(code), 2):  ### iterate over even indexes
   new_code.append(code[i])

print new_code
SuperNova
  • 25,512
  • 7
  • 93
  • 64