In: Computer Science
python 3
countries = ['mexico,'eseft,'ry,',ft,'us']
Write a statement that sorts the countries alphabetically and another statement that prints the last country in the sorted nations list.
Answer:
To sort the given list in the alphabetically order there is the pre- defined function in the python 3 that is the sorted function which automatically sorts the list in the alphabetically order.
To print the last country of the sorted list there is 2 methods:
1. The first method is to directly pass the index of the last element of the list in the print statement.( The list will always start with the index 00.
2. The second method to find out with the help of the length of the list in the print statement.The length of the list can be find out by the pre-defined len function.
Here is the code of the program:
countries=['mexico','eseft','ry','ft','us']
#statement that prints the countries in the alphabetically order by the predefined function sorted.
sorted_countries=sorted(countries)
print("Sorted list :",sorted_countries)
# statement that prints the last country in the sorted list
print("By Index method:",sorted_countries[4]) # index will be 4 because the index of the string is started from 0
# Another method by which we can print the last country in the sorted list
length=len(countries)
# here the 1 is subtracted from the length because the index is started from 0
print("By length method:",sorted_countries[length-1])
* Please refer to the screenshot of the code for proper indentation:
Here is the screenshot of the code:
Here is the output of the code: