List Comprehension - Help answering questions

Working with Loops and Sequences - What Are List Comprehensions and What Are Some Useful Functions to Work With Lists? | Learn | freeCodeCamp.org

Not understanding the List Comprehension deeply.

numbers = [1, 2, 3, 4, 5]
result = [(num, 'Even') if num % 2 == 0 else (num, 'Odd') for num in numbers]
print(result)

More specifically the part were you “declare?” the “element or iterable?”. I am not sure what exactly I am looking on so it will be hard to explain.

The above code has two tuples

(num, 'Even') and (num, 'Odd')

My question is why. I understand the conditions and loops but the code doesn’t work unless you declare this thing. Also why do the list have two different strings and num can be modified despite it being a tuple.

I feel after the basics the course start to project more and more that I know some form of programming. I.E. Javascript.

If you understand loops well, you can think of a list comprehension as a loop, except the syntax is a bit backwards. For example this list comprehension:

numbers = [1, 2, 3, 4, 5]
result = [(num, 'Even') if num % 2 == 0 else (num, 'Odd') for num in numbers]
print(result)

Would translate into a loop like this

numbers = [1, 2, 3, 4, 5]
result = [] 
for num in numbers:
    if num % 2 == 0:
        result.append((num, 'Even'))
    else: 
        result.append((num, 'Odd'))

It’s just a more concise syntax to do this. Does that help?

1 Like

Could you possible explain with placeholder code and functions. I am still a little confused and I think that might help.

if [conditional]:

    \[code\]

else

I’ve explained as clearly as I can, but you are welcome to do a web search for a better explanation. All of the keywords are the same in the comprehension and the loop, the syntax is just different.

I think it might help to start with a more simple example.

numbers = [1, 2, 3, 4, 5]
result = [] 

for num in numbers:
    result.append(num * 2)

Could you translate this for loop into a list comprehension ?

1 Like

result = [num for num in numbers num * 2]

that’s not correct, consider what part of the comprehension determines what goes in the new list

1 Like

is it the first part of the code?

Should it be:

result = [num * 2 for num in numbers]

1 Like

that’s a proper list comprehension, yes!

1 Like

So from my understanding:

numbers = [1, 2, 3, 4, 5]
result = [(num, ‘Even’) if num % 2 == 0 else (num, ‘Odd’) for num in numbers]
print(result)

(num, ’Even’) in the code means element to append

if num % 2 == 0 else (num, ‘Odd’) in the code means the conditions applied to the element that is being appene

for num in numbers in the code specifies the amount of times the expression/code before should be loop.

you need to consider (num, ‘Even’) if num % 2 == 0 else (num, ‘Odd’) all at once
this written like this means that if num % 2 == 0 is True, then (num, ‘Even’) is added to the list, else (num, ‘Odd’) is added

1 Like