Python Forum

Full Version: sort a list alphabeticaly without changing the original list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm supposed to reverse a list of countries I want to visit (alphabetical)

list = ['Poland', 'Russia', 'Germany', 'USA', 'China']
How can I do this without changing the list permanently?
first of all dont save it to built in list

lister[::-1]
please, use meaningful titles, this time I changed it for you.
don't use list as variable name. it's a built-in function and you override it
>>> countries = ['Poland', 'Russia', 'Germany', 'USA', 'China']
>>> sorted(countries)
['China', 'Germany', 'Poland', 'Russia', 'USA']
>>> countries
['Poland', 'Russia', 'Germany', 'USA', 'China']
>>> 
(Jan-27-2019, 01:23 PM)buran Wrote: [ -> ]please, use meaningful titles, this time I changed it for you. don't use list as variable name. it's a built-in function and you override it
>>> countries = ['Poland', 'Russia', 'Germany', 'USA', 'China'] >>> sorted(countries) ['China', 'Germany', 'Poland', 'Russia', 'USA'] >>> countries ['Poland', 'Russia', 'Germany', 'USA', 'China'] >>> 

the task from the Python book says

"Use sorted () to print your list in reverse alphabetical order without changing the order of the original list"

"Show that your list is still in its original order by printing it again"
>>> sorted(countries, reverse=True)
['USA', 'Russia', 'Poland', 'Germany', 'China']
When I try printing again, I don't get it in the regular order. How do I revert from reverse alphabetical to stock?

E.g:

sorted(countries, reverse=True)
['USA', 'Russia', 'Poland', 'Germany', 'China']
now... I get the reverse alphabetical order... Now, how do I get out of this variable and print the stock list again?

sorted(countries, reverse=True)
print (countries)

print ("\nHere is the original list:")
### I want the original here ###

locations = ['himalaya', 'andes', 'tierra del fuego', 'labrador', 'guam']

print("Original order:")
print(locations)

print("\nAlphabetical:")
print(sorted(locations))

print("\nOriginal order:")
print(locations)

print("\nReverse alphabetical:")
print(sorted(locations, reverse=True))

print("\nOriginal order:")
print(locations)

print("\nReversed:")
locations.reverse()
print(locations)

print("\nOriginal order:")
locations.reverse()
print(locations)

print("\nAlphabetical")
locations.sort()
print(locations)

print("\nReverse alphabetical")
locations.sort(reverse=True)
print(locations)
found out my book had a support site...