Sort lines by length
Write a Python program to sort the lines of a file by their length.
x short medium line a much longer line here
Approach
sorted(lines, key=len).
Solution
with open("story.txt", "w") as f: f.write("medium line\nx\na much longer line here\nshort\n") with open("story.txt") as f: lines = f.read().splitlines()for line in sorted(lines, key=len): print(line)x short medium line a much longer line here
Learn the concept
New to this topic? Read the lesson, then come back.