There is a big problem in your code.
sorted sorts the input list. So you are sorting input list twice.
For finding out that your list is sorted, you only need to check did you make any swap in the last iteration or not. If you don't, your list is sorted.
input_str = input("Enter elements to be sorted: ")
lst = list(map(int, input_str.split()))
raise TypeError("Please enter a list of integers only, seperated by a space!!")
if len(the_list) == 0:
elif len(the_list) == 1:
print("Only one element!!")
for i in range(len(the_list) - 1):
swapped = False
for j in range(len(the_list) - i - 1):
if the_list[j] > the_list[j + 1]:
swapped = True
the_list[j], the_list[j + 1] = the_list[j + 1], the_list[j]
if not swapped:
if __name__ == '__main__':
input_list = get_input()
print(input_list, sep=", ")
If you should print the
List is already sorted!! message, you can simply create a copy of input list (using for example:
input_list[::]) and compare that with the result of
bubble_sort function in the last part of your code.
Also, many times changing the value of the function parameter and using that like an in-out parameter is not a very good idea in the python. Because that could create many problems and misunderstandings in the future, especially when you are working with other people.
So It is better to think about using this method or returning a new sorted list from function.
But if you want to stick to the current method, don't forget to explain that in the documentation of your code clearly.
Also, for making your code more readable, maybe it is a good idea to split your
bubble_sort function to two separate functions. One checks conditions and calls the second one that really sorts the list. But it is not a necessary thing and, depends on your team and project code style and decisions, maybe make things wors. That is a thing that you can consider in your mind and think about it.