2

I have a list in list that look like this

[['a', 9] , ['b', 1] , ['c', 4] , . . ., ['z', 2]]

From here, I want to print out each list in the list line by line to look like this

['a',9]
['b',1]
. 
. 
['z',2]

I knew that I can just use loop to print it out like this:

for i in list:
   print(i)

but my question here is that, can it be done without using loop? Like just a one line that print this without interacting with loop. (I plan to use with some alert function so I want it to be in one large message containing all list , not multiple message with one list each)

I have tried this:

print(list, sep='\n')

but it doesn't separate into one line per list. I also tried this:

print('\n'.join(list))

and this error occured:

TypeError: sequence item 0: expected str instance, list found

which seem not to work with a list in list. Any idea?

5
  • 3
    For your last error, try print('\n'.join(map(str, list))) Commented Aug 7, 2019 at 14:52
  • You can post this as an answer Commented Aug 7, 2019 at 14:53
  • What do you mean when you say you want to print this in some kind of alert function? Would you redirect the output stream used by print, or how are you planning to do this? Commented Aug 7, 2019 at 14:53
  • I created a function in which it work like print() but instead of printing it out to terminal, it will send value inside this function to a chat. I avoiding loop here because I want it to be just one large message not multiple message @tobias_k Commented Aug 7, 2019 at 15:03
  • 1
    Okay, but then how will you transfer your knowledge of print to your function? E.g. does your function also support the print(*lines) syntax? '\n'.join should work, though. depending on how your chat works, you could also try print(..., file=your_chat_stream) Commented Aug 7, 2019 at 15:19

2 Answers 2

8
lst = [['a', 9] , ['b', 1] , ['c', 4]]

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

Prints:

['a', 9]
['b', 1]
['c', 4]
Sign up to request clarification or add additional context in comments.

Comments

3

You were almost there, just add some list comprehension:

my_list = [['a', 9] , ['b', 1] , ['c', 4] , . . ., ['z', 2]]
print('\n'.join(str(el) for el in my_list ))

1 Comment

This one work well with my chat function but there are too many element in list it will show .. at the last line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.