4

I'm having a problem sorting list in Python here's my code:

lista = [ 1, .89, .65, .90]

for x in lista.sort():
    print (x)

Error is:

TypeError: 'NoneType' object is not iterable

3 Answers 3

7

The sort method sorts the list in-place; it always returns None. What you can do:

lista = [ 1, .89, .65, .90]
lista.sort()

for x in lista:
    print (x)

Or, as @Delgan pointed out, you can use the sorted function, which returns the sorted list:

lista = [ 1, .89, .65, .90]

for x in sorted(lista):
    print (x)
Sign up to request clarification or add additional context in comments.

1 Comment

Or use sorted() instead.
4

list.sort() only change the list but return None, you need:

lista = [1, .89, .65, .90]
lista.sort()

for x in lista:
    print(x)

Or simply use sorted():

lista = [1, .89, .65, .90]

for x in sorted(lista):
    print (x)

sorted() return a new list but sorted, note that it doesn't change the current list.

Comments

3

.sort() doesn't return anything. If you want to modify the list to be sorted you can do

lista = [ 1, .89, .65, .90]
lista.sort()
for x in lista:
    print (x)

or if you want to keep the list in the original order you can use sorted which returns a new list of the sorted elements:

lista = [ 1, .89, .65, .90]

for x in sorted(lista):
    print (x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.