why i have the output of [None, None, None]

J

Jussi Piitulainen

length said:
x=['','x1','x2','x3',' ']
x ['', 'x1', 'x2', 'x3', ' ']
[print("ok") for it in x if it.strip() !=""]
ok
ok
ok
[None, None, None]

i understand there are three 'ok' in the output,but why i have the
output of [None, None, None]

It's a list containing the values from three invocations of print.
You get it because you asked for it.

|>>> print("ok") == None
|ok
|True
|>>> print("ok") != None
|ok
|False
|>>> [(print("ok") or "die") for x in (1,2,3)]
|ok
|ok
|ok
|['die', 'die', 'die']
|>>> [print("ok") for x in (1,2,3)] and print("What do you want it to be?")
|ok
|ok
|ok
|What do you want it to be?
|>>>

(That last one actually returns None to the interpreter, which
promptly does not print it.)
 
R

Rustom Mody

This is called imperative programming:

for it in x:
.... if it.strip() != '':
.... print ("Ok")

This is called functional programming:
[y for y in x if y.strip() != '']
['x1', 'x2', 'x3']

What you have is a confusion:
print is imperative
comprehension is functional
You should not mix them like that
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,817
Latest member
AdalbertoT

Latest Threads

Top