Friday, 18 December 2020

Python: Sort a list but do not affect original one

In my previous post, I explained sort function which sort the given list. One thing to note with sort function is, once you call sort function on a list the affect is reflected in original list.

 

But what if you want to sort a list without affecting the actual list, you can use ‘sorted’ function.

 

sorted_demo.py

country_names = ["India", "Australia", "Sri Lanka", "Itali"]

print("Original list")
print(country_names)

print("\nlist after sorting")
print(sorted(country_names))

print("\nOriginal list")
print(country_names)

 

Output

$python3 sorted_demo.py 
Original list
['India', 'Australia', 'Sri Lanka', 'Itali']

list after sorting
['Australia', 'India', 'Itali', 'Sri Lanka']

Original list
['India', 'Australia', 'Sri Lanka', 'Itali']

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment