KRISHNA I
KRISHNA I

Reputation: 67

printing list elements in python with a single line code

I am new to Python. I would to print all elements in list using a single line of code. You may use lambda function.

a = [1,2,3,4]
for each in a:
    print(each)

Here, I used two lines of code What I want is a single line of code to get the same output (preferably lambda function)

output required:

1

2

3

4

Upvotes: 1

Views: 5933

Answers (3)

S.Desi
S.Desi

Reputation: 1

Try this print(''.join(map(str, a)))

Upvotes: -1

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Try this just using print:

print(*a, sep=' ')

print accepts sep key that will put between printing of each element of an iterable.

so the above code output will be

1 2 3 4

You can use ',' or \n(new line) to print between each charater.

it means:

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

output will be:

1
2
3 
4

Upvotes: 3

Daweo
Daweo

Reputation: 36390

If you have to use lambda AT ANY PRICE, then (using Python 3):

a = [1,2,3,4]
list(map(lambda x:print(x),a))

However, if one liner is enough for you keep in mind that such code:

a = [1,2,3,4]
for each in a: print(each)

is legal Python code, producing same result. Yet another option is converting int to str and joining them:

print('\n'.join(map(str,a)))

Upvotes: 2

Related Questions