Python: Sort a list and print it out with a for loop – 'NoneType' object is not iterable'
Question:
I have created a random list with numbers:
numbers = [8, 2, 17, 99, 12]
And I want to print them out with a for loop and permanently sort the numbers in increasing order.
I was able to do that, but i’m not sure if I am using the short way to do that.
numbers.sort()
for number in numbers:
print (number)
I solved that with the code above, but my first instict was to do this:
for number in numbers.sort():
print (number)
But the following error was found: TypeError: ‘NoneType’ object is not iterable.
Is there a way to sort the numbers in the "for placeholder_variable in variable" or the only way is with the first code? I have to sort them first and then make the for loop?
Thank you.
Answers:
what you want is:
for number in sorted(numbers):
print (number)
numbers.sort()
sorts your list in place but does not return anything itself.
I have created a random list with numbers:
numbers = [8, 2, 17, 99, 12]
And I want to print them out with a for loop and permanently sort the numbers in increasing order.
I was able to do that, but i’m not sure if I am using the short way to do that.
numbers.sort()
for number in numbers:
print (number)
I solved that with the code above, but my first instict was to do this:
for number in numbers.sort():
print (number)
But the following error was found: TypeError: ‘NoneType’ object is not iterable.
Is there a way to sort the numbers in the "for placeholder_variable in variable" or the only way is with the first code? I have to sort them first and then make the for loop?
Thank you.
what you want is:
for number in sorted(numbers):
print (number)
numbers.sort()
sorts your list in place but does not return anything itself.