froycard
froycard

Reputation: 435

problems sorting a list elements

In Python I found these two pieces of code quite weird:

mylist = list (str (2132))
mylist. sort ()
print mylist

>>> ['1','2','3','4']

and

print (list (str (2132))). sort()

>>> None

What is the difference?

It yields None inclusive when I declare a variable like this:

mylist = list (str (2132)).sort ()

It seems that sort() only works in very precise way

Upvotes: 0

Views: 91

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

In python, sort() is a list method that sorts a list in-place and returns None, while sorted() returns a sorted copy of a collection without changing the original;

>> a = [4,5,3]
>> sorted(a)
[3, 4, 5]

>> a 
[4, 5, 3]

>> a.sort()
>> a
[3, 4, 5]

Upvotes: 2

Related Questions