zhu
zhu

Reputation: 41

How to sort only positive numbers from a list?

I am trying to make a list of only sorted positive list when the user gives positive and negative integers in that list. For example, if the user gave "10 -7 4 39 -6 12 2" my program would only sort the positive numbers and give out '2 4 10 12 39'. So far this is what my code looks like:

list = input().split()

positive_list = []

for i in range(list):
    if list[i] > 0:
        positive_list.append(list[i])
        i+=1
positive_list.sort()
print(positive_list)

Upvotes: 2

Views: 1847

Answers (2)

Grismar
Grismar

Reputation: 31354

You have several issues:

  • you have a variable that's named the same as a basic type (list), which shadows the type; pick a better name
  • for i in range(my_list): doesn't do what you think; you could do for i in range(len(my_list)):, but you can also just for n in my_list: and n will be every element in my_list in turn
  • your user enters text, you'll need to turn those strings into integers before comparing them to other integers, using int()
  • you do for i .. but also i += 1 you don't need to increment the for-loop variable yourself.

Look into list comprehensions, they are perfect for what you're trying to do in a more complicated way, to construct positive_list.

Your solution could be as simple as:

print(sorted([int(x) for x in input().split() if int(x) > 0]))

But staying closer to what you were trying:

numbers = [int(x) for x in input().split()]
sorted_positive_numbers = sorted([x for x in numbers if x > 0])
print(sorted_positive_numbers)

If you insist on a for-loop instead of a list comprehension:

numbers = [int(x) for x in input().split()]
positive_numbers = []
for number in numbers:
    if number > 0:
        positive_numbers.append(number)
print(sorted(positive_numbers))

Upvotes: 3

Nikola Selic
Nikola Selic

Reputation: 51

Rename list to something other than that. list is a python keyword. For example list_new or list_temp

My suggestion is to try it like this:

positive_list = []
for num in listNew:
  if num > 0:
    positive_list.append(num)

positive_list.sort()

Upvotes: 0

Related Questions