Search code examples
pythonfor-loopenumerate

How do I check two conditions at the same time in a for loop in python?


I have a list of words in their labels '0' or '1'. I want to access and count how many words in my list are ending in -a whose label is 1 and how many words ending in -o whose label is 0. My idea was to access the first and second element of the list using enumerate as below, but that does not work. How could I do this?

ts=['0','carro','1', 'casa', '0', 'mapa','1','fantasma']

obj1 = enumerate(ts)

    for j, element in obj1:
        if j=='0' and element[-1]=='o':       

Solution

  • If I understand it correctly, you have a mixed list where the odd elements are the labels, and the pair elements are words. You want to operate some code (count and more) when you meet either of the two conditions:

    1. label = "0", word ends with "o"
    2. label = "1", word ends with "a"

    Following @Olvin Roght suggestion (who commented under your question):

    for j, element in zip(ts[0::2], ts[1::2]):
        if (j == "0" and element[-1] == "o") or (j == "1" and element[-1] == "a"):
            # your code here