-2

I have the following list:

result_lines = ['hello', 'bye']

I trying to form a one-liner to print the elements of the list as follows:

print(line for line in result_lines)

Expected Result:

hello

bye

Output (that I am getting):

<generator object execute_commands.. at 0x7f9e37a9b900>

EDIT:

Also, how is the above approach different from :

for line in result_lines:
    print(line)

I am not able to figure out why this is happening. Any help is appreciated.

S M Vaidhyanathan
  • 320
  • 1
  • 4
  • 13
  • 1
    Surround the everything inside print in brackets, so for example `print([line for line in result_lines])` should work. For more check out [list compehensions](https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20comprehensions#list-comprehensions) – c_48 Dec 21 '21 at 18:25
  • 2
    `line for line in result_lines` is a generator expression, so it prints a representation of the generator object created by the expression. Since you want to print each element of the generator, expand it into a sequence using brackets. Note that you can get the same result by simply `print(result_lines)` – Pranav Hosangadi Dec 21 '21 at 18:27
  • 2
    Your question title says "Not able to print list elements in for loop"; but you showed us code that is **not a for loop** and complained that it doesn't give you the desired output, then you showed code that **is** a for loop and that **does, in fact, work**. – Karl Knechtel Dec 21 '21 at 18:35

3 Answers3

2

As you see, you have a generator. You need to create a list from the generator.

print([line for line in result_lines])

or

print(list(line for line in result_lines))

Also, you don't really need a generator/loop here, you can just do

print(result_lines)
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

You may try like this,

result_lines = ['hello', 'bye']
print(*result_lines, sep = "\n")

use * to pass all elements without binding them in a list and use sep="\n" to every element onto the next line.

MUsmanTahir
  • 75
  • 10
1

In Python if you want to work with list comprehension you have to add square braces, like this...

list_ = [element for element in iterable]

...that's equivalent to...

list_ = list(element for element in iterable)

...and to...

list_ = [] # equivalent to list()
for element in iterable:
    list_.append(element)

In you case you have to add square brackets, like this:

print([line for line in result_lines])

But you can also solve your problem using the built-in function print, like this:

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

since in Python you can use * operator to convert an iterable to a printable iterable.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28