Posts: 3
Threads: 1
Joined: Jan 2019
Jan-27-2019, 01:15 PM
(This post was last modified: Jan-27-2019, 01:19 PM by buran.)
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?
Posts: 5,151
Threads: 396
Joined: Sep 2016
first of all dont save it to built in list
lister[::-1]
Recommended Tutorials:
Posts: 8,160
Threads: 160
Joined: Sep 2016
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']
>>>
Posts: 3
Threads: 1
Joined: Jan 2019
Jan-27-2019, 01:28 PM
(This post was last modified: Jan-27-2019, 01:31 PM by Holmen.)
(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"
Posts: 8,160
Threads: 160
Joined: Sep 2016
>>> sorted(countries, reverse=True)
['USA', 'Russia', 'Poland', 'Germany', 'China']
Posts: 3
Threads: 1
Joined: Jan 2019
Jan-27-2019, 01:49 PM
(This post was last modified: Jan-27-2019, 01:56 PM by Holmen.)
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...
|