-3

I am trying to understand when should one use list comprehension. a lot of time, it is convenient and save lines. But sometimes, it does not work as expected?

if I have:

listA = ['1', '2', '3', '4']

I can use a for loop

for i in listA:
    print(i)

obviously this will give me:

1
2
3
4

what if I try:

print(i for i in listA)

but this won't give me the same result?

<generator object <genexpr> at 0x102a3b3b8>

How should I understand this?

My additional question is: if I have a for loop followed by one line of codes, can one always write it in a way using comprehension?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
jxie0755
  • 1,682
  • 1
  • 16
  • 35

3 Answers3

1

You don't have a list comprehension. You passed in a generator expression to print(). The print() function does not iterate over any arguments you pass in; it only sends the str() conversion to stdout.

If you wanted to send all values in the generator to print(), use *(...):

print(*(i for i in listA))

Here that's overkill, you could just do the same for the values in listA:

print(*listA)

Both will print the values with the default separator, a space. If you wanted to have newlines, tell print() to use \n as the separator:

print(*(i for i in listA), sep='\n')
print(*listA, sep='\n')

And no, not every for loop is suitable to be converted to a list comprehension. A list comprehension creates a new list object, and not all loops build lists.

If you have a list of the form:

some_name = []
for <target> in <iterable>:
    some_name.append(<expression>)

then you can convert that to a list comprehension:

some_name = [<expression> for <target> in <iterable>]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

A generator is an object that can be iterated over. It is not intended to be printed.

List comprehensions come in two forms, with and without brackets:

print(i for i in listA)
print([i for i in listA])

The first one produces an iterator object while the other produces an actual list.

For your problem you could do:

print(*listA, sep='\n')

In general, list comprehensions should be avoided when they make code obscure. Why not use a simple for loop?

plan
  • 269
  • 2
  • 10
0

You can do the following:

listA = ['1', '2', '3', '4']
# option 1
print(*listA, sep='\n')
# option 2
for p in listA: print (p)
SuperKogito
  • 2,998
  • 3
  • 16
  • 37