Ignore certain indices in a Python list

Asked

Viewed 83 times

0

I have the following situation:

  • I have a list of 64 items and I want the first two values to be displayed and all the other ones after 2.

An example would be:

lista = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]

I wish the values to be displayed: [1,2,5,6,9,10,13,14,17,18,21,22]

I sincerely thank you for your help.

1 answer

3


[lista[i:i+2] for i in range(0, len(lista), 4)]

First, I used the list compression to generate the new list. The values of this list will always be the values of the original list in the indexes i until i+2 for each value of i. With the structure for defined that the values of i will be 0 to the length of the original list, with a step of 4. That is, to i=0, list the values on indices 0 and 1. The next value of i will be 4, adding the values of indices 4 and 5, so indices 2 and 3 were ignored. The same happens for higher values of i.

See working on Repl.it.

  • Anderson, thank you so much! It worked perfectly as expected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.