Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (50.2k points)

I am currently working with list format data and let's suppose I am having a list and I want to sort the elements from lowest to highest. How can I approach that?

The list: [-5, -23, 5, 0, 23, -6, 23, 67]

The desired list: [-23, -6, -5, 0, 5, 23, 23, 67]

This is the below code I have executed:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]

new_list = []

minimum = data_list[0]  # arbitrary number in list 

for x in data_list: 

  if x < minimum:

    minimum = value

    new_list.append(i)

However, the above goes through only once, and this is what I get:

new_list = [-23] 

This is where I am getting stuck. Kindly help me!!

1 Answer

0 votes
by (108k points)

You can use the while loop so that you can go inside the list and after that, you can simply create an empty list that will hold new sorted values, take the reference from the below code:

data_list = [-5, -23, 5, 0, 23, -6, 23, 67]

new_list = []

while data_list:

    minimum = data_list[0]  # arbitrary number in list 

    for x in data_list: 

        if x < minimum:

            minimum = x

    new_list.append(minimum)

    data_list.remove(minimum)    

print new_list

If you are a beginner and want to know more about Python, then do refer to the Python training course that will help you out in understanding the topic in a better way.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Jul 22, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...