Search code examples
pythonlistlist-comprehension

Transform solved code using loop and conditionals to list comprehension


I have this code already solved using traditional methods:

edades = [10, 25, 49, 16, 60]
mayores_edad = []
for edad in edades:
    if edad >= 18:
        mayores_edad.append(1)
    else:
        mayores_edad.append(0)
print("Mayores de edad:", mayores_edad)

Now I want to do the same but using list comprehension. I already did this:

mayores_edad_por_compresion = [x if (x >= 18) == 1 else 0 for x in edades]
print(mayores_edad_por_compresion)

The problem is that the result is this: [10, 0, 0, 16, 0] and I need it to be this [0, 1, 1, 0, 1] like the traditional one.

What am I doing wrong? Thanks in advance.


Solution

  • Simply put, you want the value in the list to be 1 instead of x when the condition is true, so you should write

    mayores_edad_por_comprehension = [1 if (x >= 18) else 0 for x in edades]
    

    instead. Note that the comparison ==1 is not necessary and should be removed.

    In addition, in this particular case, you can just convert the condition to an integer.

    mayores_edad_por_comprehension = [int(x >= 18) for x in edades]
    

    Whether this is better/clearer than the other approach is opinion-based, but it's good to know this alternative method.