Skip to content
Advertisement

What is the difference between normal loops and list comprehension?

x = 'aaaabbbccd'
new = list(itertools.groupby(x))
[print(i) for i in new]
for i in new:
    print(i)

The result for line 2 is is something like:

('a', <itertools._grouper object at 0x0000014163062EB0>)
('b', <itertools._grouper object at 0x0000014163062FD0>)
('c', <itertools._grouper object at 0x0000014163062F70>)
('d', <itertools._grouper object at 0x0000014162991BB0>)
[None, None, None, None]

Where as the result for the normal for loop is:

('a', <itertools._grouper object at 0x0000014163062EB0>)
('b', <itertools._grouper object at 0x0000014163062FD0>)
('c', <itertools._grouper object at 0x0000014163062F70>)
('d', <itertools._grouper object at 0x0000014162991BB0>)

Why do I get the extra [None, None, None, None] in case of list comprehension?

Advertisement

Answer

A list comprehension is used to comprehend (Make) a list. It is useful only when making lists. However, here you are not making a list, so it is not recommended to use list comprehension. You only print the value and not store it as a list. Here, use a for a loop.

The reason you get None is – the list comprehension basically becomes a list of print() functions like [print(...),print(...)....]

So when you call them it becomes like – print(print(...)), which, if you try this code, will return a None along with the output.

So, do not use list comprehension unless you are using it to build a list.

References – This and That

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement