0

I am working a Rubik's cube assignment and I need help to complete one of the steps. I need to iterate through a list by comparing the elements and skipping every 5th element. so far I was able to find this:

newList =['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']
for elem in newList[ : : 5]:
    print elem

using this, I only get every 5th element to be printed, which is the opposite of what I want. thanks

slider
  • 12,810
  • 1
  • 26
  • 42
Plagga
  • 1
  • 2

4 Answers4

4
[newList[each] for each in range(len(newList)) if each % 5 != 4]

i am using python3 though, try if it works for you too.

as other answers suggested, using enumeration results better:

[each for index, each in enumerate(newList) if index % 5 != 4]
Boyang Li
  • 157
  • 2
  • 11
  • The 5th element means `each == 4`, which `each % 5 != 0` and will not be skipped. You will be skipping every 6th element `5` instead. I think you're looking for `(each + 1) % 5 != 0` instead. – r.ook Oct 12 '18 at 02:41
1

You can make use of the enumerate function as you're iterating, so that you know which index the element has in the list. Then you can perform your checks easily:

for index, elem in enumerate(newList):
    if index % 4 == 0:
        # do something
slider
  • 12,810
  • 1
  • 26
  • 42
  • It still prints only every 5th element. but when I tried if index %4 != 0: it worked, but did not start from '0' – Plagga Oct 12 '18 at 03:02
  • @Plagga That was just to demonstrate what you could do with `enumerate`. Since this is a homework assignment, I thought I'd leave it to you to figure out how you could use `index` to your advantage to get your desired result. – slider Oct 12 '18 at 03:09
1

you can use the index of the element to skip.

for index, elem in enumerate(newList):
    if index != 4:    
        print elem

Hope this helps! Cheers!

SanthoshSolomon
  • 1,383
  • 1
  • 14
  • 25
0

Here is how I did it.

    array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

    count = 1

    for i in array1:
        if count % 5 != 0:
           count += 1
           print(i)
        else:
           count += 1
Adam
  • 395
  • 4
  • 9