my code is....
names = ['ali', 'parham', 'hasan', 'farhad']
print('names: ', [print(i) for i in names])
and my output is this...
ali
parham
hasan
farhad
names: [None, None, None, None]
but i want this....
names: ali, parham, hasan, farhad
why what are in the list is 'None'?!
and why the name are in the above lines?!
CodePudding user response:
When you do print('names: ', [print(i) for i in names])
the following happens: To do the first print
Python has to evaluate the arguments of the function. The second argument is [print(i) for i in names]
. Here you loop over the names, print them and put the result of the call to print
in the list. This result is always None
.
So after this first step all the names are printed and then you're virtually left with print('names: ', [None, None, None, None])
. Now print
will output exactly that.
If you want to combine the entries of a list to a string use the strings join
method. Here are some examples from the interactive interpreter.
>>> '-'.join(['A', 'B', 'C'])
'A-B-C'
>>> 'x'.join(['A', 'B', 'C'])
'AxBxC'
>>> ' '.join(['A', 'B', 'C'])
'A B C'
>>> values = ['x', 'yy', 'zzz']
>>> ' '.join(values)
'x yy zzz'
>>> names = ['ali', 'parham', 'hasan', 'farhad']
>>> ', '.join(names)
'ali, parham, hasan, farhad'
So what you need here is:
print('names:', ', '.join(names))
or with an f-string
print(f"names: {', '.join(names)}")
This will give you names: ali, parham, hasan, farhad
.