Is there a python 3 for loop one-liner that doesn't produce a list?

Viewed 223

I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this:

for x in range(10):
  print(x) 

as this:

print(x) for x in range(10)

I do not want to return a list as the arr = [x for x in X] list comprehension syntax does.

EDIT: I'm not actually in that specific case involving print(), I'm interested in a generic pythonic syntactical construction for

method(element) for element in list
4 Answers

No, there isn't. Unless you consider this a one liner:

for x in range(6): print(x) 

but there's no reason to do that.

Looks like you are looking for something like map. If the function you are calling returns None, then it won't be too expensive.

Map will return an iterator, so you are just trying to consume it. One way is:

list(map(print, range(6)))

Or using a zero length deque if you don't want the actual list elements stored.

from collections import deque

deque(map(print, range(6)), maxlen=0)

For your specific case to print a range of 6:

print(*range(6), sep='\n')

This is not a for loop however @Boris is correct.

What you are looking for is a generator expression that returns a generator object.

print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0>

To see the values

print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9

Pros:

  • Extremely Memory Efficient.
  • Lazy Evaluation - generates next element only on demand.

Cons:

  • Can be iterated over till the stop iteration is hit, after that one cannot reiterate it.
  • Cannot be indexed like a list.

Hope this helps!

Related