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?
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 ?
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