-1

Here's a simple python code:

random_list = ["yes", "no", "yessir", "nope", "maybe"]
print(random_list)

This is basics, we created a list and we printed it. The output? Well the expected output is obviously:

['yes', 'no', 'yessir', 'nope', 'maybe']

but if you agree with me, and I am sure you do, the result looks ugly. What if I want the output to look like this? :

yes
no
yessir
nope
maybe

I want to remove the brackets, the speech marks, and I want the list to use line breaks like: \n

You could do this:

print(random_list[0])
print(random_list[1])
print(random_list[2])
print(random_list[3])
print(random_list[4])

But what if the list is extremely long, or you simply do not KNOW how long it is? I am sure you can use len() and 'for' loops to do something, but I can not remember... If you know a way to list the items in this better layout, I will definitely appreciate it. I am not new to python, but I always get mixed up. If you have some advanced methods like using lambda or something, you can share it too. Thanks

Hyperba
  • 89
  • 3
  • 12

2 Answers2

2

Put a newline between all elements:

print("\n".join(random_list))

Or, to be more robust with regard to the types inside the list:

print("\n".join(map(str, random_list)))
mcsoini
  • 6,280
  • 2
  • 15
  • 38
0

Yes, you can do it with for loops:

for item in random_list:
    print(item)
Ukulele
  • 612
  • 2
  • 10
  • 1
    The list comprehension is not the best solution. There's no need to create a list containing only elements with the value `None` and then throw that list away. – Matthias Apr 07 '22 at 14:23
  • I suppose so. The for loop is better – Ukulele Apr 07 '22 at 14:24
  • 1
    I think for this particular problem the second option is not very nice. Sure it will work, but it will be confusing on why using a list comprehension if we are not creating a list. two lines are sometimes better than one. –  Apr 07 '22 at 14:24