0

I know for some of you it may be a silly question, but it is a confusion for me. how it works without assigning to a variable and how it's updated value is usable.

This code print sorted list

Python code

data=[23,11,32,89,52,99]
data.sort()
print(data)
1

4 Answers 4

2

It works in the same way as this code:

class Thing:
    def __init__(self, value):
        self.value = value
    def modify(self):
        self.value += 1

data = Thing(5)
print(data.value)  # prints '5'

data.modify()
print(data.value)  # prints '6'

Basically, it modifies the internal state of the object. The list object stores its values in some region of memory (that is, in some internal variable), and the sort method messes with this internal variable in such a way that the list's values are sorted.

Sign up to request clarification or add additional context in comments.

Comments

2

Your variable, data, is a list. A list has a method called sort, which sorts the list and updates those values. You can see all methods by entering dir(data) or even directly on the data type dir(list).

This is different than the function sorted(), which sorts the list and returns the sorted value, but does not update the original list.

data=[23,11,32,89,52,99]
print(sorted(data))  # Returns sorted list
print(data)  # Original is not modified
data.sort()  # Modifies original
print(data)

Comments

1

That's because list.sort() method modifies the list in-place. Other method like sorted() will not modify the list. For example:

data=[23,11,32,89,52,99]
sorted(data)
print(data)

Out:
[23, 11, 32, 89, 52, 99]

Assigned:

data=[23,11,32,89,52,99]
data = sorted(data)
print(data)

Out:
[11, 23, 32, 52, 89, 99]

So it depends on how the method is structured. Hope it helps.

Comments

0

List is an object

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass
    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

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.