1

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

3
  • 5
    Why preferably a lambda function? Commented Jan 9, 2019 at 13:49
  • 7
    print(*a, sep='\n') Commented Jan 9, 2019 at 13:50
  • Possibly better suited for code golf. Commented Jan 9, 2019 at 21:53

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

I dont want output on single line but the code on single line.
like for each in a: print a
@KRISHNAI I already told you the solution. but I also updated my answer.
2

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)))

1 Comment

Thanks. The reason why I want to use lambda is because my program has lot of for loops of printing lists. Anyway thanks above mentioned methods are helpful to me
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.