1

I have a python list like this

colors = ['red', 'blue']

and a number, say j, which increases by 1 for each step of a loop. What I am looking for is a code which calls colors[0] when j = 0, colors[1] when j = 1 and than again colors[0] when j = 2 and so on as better illustrated in what follows

j = 0 -> color[0]

j = 1 -> color[1]

j = 2 -> color[0]

j = 3 -> color[1]

j = 4 -> color[0]

...

Could you provide me an advice, please?

Stefano Fedele
  • 5,971
  • 8
  • 26
  • 45

4 Answers4

2

You can also use cycle to endlessly cycle through your list.

from itertools import cycle

colors = cycle(['red', 'blue'])
for _ in range(5):
    j = next(colors)
    print(j)

red
blue
red
blue
red
gold_cy
  • 12,080
  • 3
  • 20
  • 42
1

This is easily done by using mod 2 of j in the element selector (odd numbers will return 1, even numbers will return 0):

colors = ['red', 'blue']
for j in range(5):
    print(j % 2, colors[j % 2])
    # 0 red
    # 1 blue
    # 0 red
    # 1 blue
    # 0 red
match
  • 8,748
  • 2
  • 21
  • 38
0
for i in range(n):
    # code..
    j = i % 2

What this does is map the numbers to their remainder when divided by 2, which alternates between 1 for odd numbers and 0 for even numbers.

jh316
  • 691
  • 4
  • 7
0

I will try to solve this in different approach. I simply applied even/odd method...If J is even print blue else print red

colors = ['red', 'blue']
for x in range(6):
  if x%2==0:
      
      firstElement = colors[0]
      print(firstElement)

  else:
      print(colors[1])
 
Bhargav
  • 500
  • 2
  • 12
  • If this question is time-critical, then it is worth noting that this method is about 30% slower than either using `cycle` or using the mod value 'directly' as the element selector. – match Dec 29 '21 at 16:07
  • Yes, I agree with you...But, I just want to keep simple. because, author not mentioned any constraints... – Bhargav Dec 29 '21 at 16:11