Mohammad
Mohammad

Reputation: 105

Printing a list on a new line

I have a list that i call a function on to make it print out the list in lexicographic order. Lexicographic is basically a sort() which isn't important but I want this list sorted in a new line with every entry. Right now it just prints like

['(011)', '(022)', '(040)', '(04344)', '(044)', '(04546)', '(0471)', '(080)', '(0821)'] 

when i want

011
022
etc

I tried using a for loop but that made it worse. I tried

print (lexicographic(uniquelist), sep = '\n') 

but that didn't change anything. I even tried making a new empty list and appending but that didn't go anywhere the new line feature works without the function "lexicographic" call.

print(lexicographic(uniquelist), sep = '\n')

(04344)
(080)
(044)
(011)
(0821)
(022)
(040)
(0471)
(04546)

expected this but sorted lexicographically and on a new line

Upvotes: 1

Views: 73

Answers (3)

Alexandre B.
Alexandre B.

Reputation: 5500

If you just want to print each element of your list on one line, you can use: [print(elt) for elt in list]

Here one example which also remove brackets:

list = ['(0821)', '(011)', '(080)', '(022)',  '(04344)', '(040)', '(044)', '(04546)', '(0471)', ]

# sort 
list.sort()

# Print each element per line
[print(elt[1:-1]) for elt in list]
# 011
# 022
# 040
# 04344
# 044
# 04546
# 0471
# 080
# 0821

Hope that help !

Upvotes: 1

Within your lexographic function, try doing

for l in lexographically_sorted_list:
    print (l)

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88468

There are two ways you can do what you like:

uniques = ['(04344)', '(080)', '(044)', '(011)',
           '(0821)', '(022)', '(040)', '(0471)',
          '(04546)']

# Join with new lines and print
print('\n'.join(sorted(uniques)))

# A classic loop, nothing wrong with this
for item in sorted(uniques):
    print(item)

Output is:

(011)
(022)
(040)
(04344)
(044)
(04546)
(0471)
(080)
(0821)

If you do not want the parens,

for item in sorted(uniques):
    print(item[1:-1])

Upvotes: 1

Related Questions