-1

I have a problem with a pice of my code. I have a boolean list and need to know which index is true.

lst = [True, True, False]

for element in lst:
 print(lst.index(element))

why the output is 0,0,2?

I just need output 0,1,2

  • how is index 2 "True"? – acushner Mar 10 '22 at 16:09
  • index 2 is "False". Here i'm just printing the index of every element in the list. But the second True should have index 1 but its printing index 0 – Aleksandra Tkaczyk Mar 10 '22 at 16:12
  • You're printing the index of element for each element of the list. When element is true, it will return 0 (the first index to be True). When element is false, it will return 2 (the first index to be False). In total, it returns 0, 0, 2. I suggest you check that other post : https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list – Mateo Vial Mar 10 '22 at 16:12

2 Answers2

1

Do this.

lst = [True, True, False]

for idx, val in enumerate(lst):
    if val == True:
        print(idx)

The output

0
1
Lion Lai
  • 1,862
  • 2
  • 20
  • 41
0

This will print only the true, so I'm not sure if its exactly what you need. If you provide more context we could probably help get a better answer for your specific problem.

lst = [True, True, False]

for element in lst:
    if element == True:
        print(element)
ArchAngelPwn
  • 2,891
  • 1
  • 4
  • 17