Coding in Python: a comprehensive Beginners Guide to Learn the Realms of Coding in Python


Download 1.25 Mb.
Pdf ko'rish
bet14/48
Sana30.01.2023
Hajmi1.25 Mb.
#1140552
1   ...   10   11   12   13   14   15   16   17   ...   48
Bog'liq
Coding in Python A Comprehensive Beginners Guide to Learn the Realms

The sort() Method
The sort method of Python makes it fun to sort a list. I will use the same list
of officeitems and experiment on it to see how the list gets organized. The
sort() method sorts lists in an alphabetical order.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
print(officeitems)
officeitems.sort()
print(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/sample.py
['printer', 'scanner', 'fan', 'table', 'table lights']
['fan', 'printer', 'scanner', 'table', 'table lights']
>>>
The sort() method has changed the list into a perfect alphabetical order. You
cannot revert to the original order once you have sorted your list. The sort()
can also be used to order the list in the reverse alphabetical order.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
print(officeitems)
officeitems.sort(reverse=True)
print(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/sample.py
['printer', 'scanner', 'fan', 'table', 'table lights']


['table lights', 'table', 'scanner', 'printer', 'fan']
>>>
Coupled with the sort() method is the sorted() function. While the sort()
method permanently reorders a list, the sorted() function makes temporary
changes.
officeitems = ['printer', 'scanner', 'fan', 'table', 'table lights']
print(officeitems)
print(sorted(officeitems))
print(officeitems)
= RESTART: C:/Users/saifia computers/Desktop/sample.py
['printer', 'scanner', 'fan', 'table', 'table lights']
['fan', 'printer', 'scanner', 'table', 'table lights']
['printer', 'scanner', 'fan', 'table', 'table lights']
>>>
You can see that the sorted() function temporarily changed the order of the
list. When I printed the list without the sorted() function, it comes back into
its original order.

Download 1.25 Mb.

Do'stlaringiz bilan baham:
1   ...   10   11   12   13   14   15   16   17   ...   48




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling