1
items = [ "Abby","Brenda","Cindy","Diddy" ]

for item in items:
    print(item)

I use to write this statement for output items.

Is there a way to merge both print and loops. Something like:

print(item for item in items)

Correct me if I am wrong!

Sanjit Prasad
  • 398
  • 2
  • 12

2 Answers2

8

You can use the argument unpacking operator * (also called the "splat" operator):

>>> items = [ "Abby","Brenda","Cindy","Diddy" ]
>>> print(*items, sep='\n')
Abby
Brenda
Cindy
Diddy
>>> 

You need to set sep='\n' too because print defaults to separating arguments with spaces.


Just for completeness, when you do:

print(item for item in items)

It will create a generator over the items in items and then print that:

>>> items = [ "Abby","Brenda","Cindy","Diddy" ]
>>> print(item for item in items)
<generator object <genexpr> at 0x5ffffe02ee08>
>>>

If you want to use this in Python 2.x, you will need to import print_function from the __future__ module first:

>>> from __future__ import print_function
>>> 
>>> items = [ "Abby","Brenda","Cindy","Diddy" ]
>>> print(*items, sep='\n')
Abby
Brenda
Cindy
Diddy
>>>
2

You can use list comprehension:

items = ["Abby", "Brenda", "Cindy", "Daddy"]
[print(item) for item in items]

And. . . you only need to add two characters to your code!

There is a good discussion about list comprehension versus generator expressions here:

Generator Expressions vs. List Comprehension

I think either is valid. A genexp may be more efficient in this case, but the listcomp more clearly documents what you are doing.