Omer H Omer H - 6 months ago 12
Python Question

What's the difference between Python list comprehension and normal loop?

The next loops returns a value of

3
for
count
parameter:

for line in textfile.text.splitlines():
count += 1 if 'hostname' in line else 0


However trying to to do the same using list comprehension returns
1
:

count += 1 if ['hostname' in line for line in textfile.text.splitlines()] else 0


Where did I go wrong?

Answer

List comprehensions are shortcut for list creation. The following is (roughly) equivalent:

result = []
for item in l:
    if condition(item):
        result.append(item.attribute)

result = [item.attribute for item in l if condition(item)]

So your code

count += 1 if ['hostname' in line for line in textfile.text.splitlines()] else 0

would be the same as

result = []
for line in textfile.text.splitlines():
    result.append('hostname' in line)

count += 1 if result else 0

which is obviously not the same as

for line in textfile.text.splitlines():
    count += 1 if 'hostname' in line else 0

instead you could do things like

count += sum([1 for line in textfile.text.splitlines() if 'hostname' in line])
Comments