Write a program that extracts the last three items in the list sports and assigns it to the variable last. Make sure to write your code so that it works no matter how many items are in the list. sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey']
Answers
Python:
def myFunction(sports_list):
last = [sports_list[-1], sports_list[-2], sports_list[-3]]
return last
sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey']
last = myFunction(sports)
print(str(last))
Here is one way to write a Python program that extracts the last three items in the list "sports" and assigns it to the variable "last":
First, import the "sports" list.
sports = ['cricket', 'football', 'volleyball', 'baseball', 'softball', 'track and field', 'curling', 'ping pong', 'hockey']
Next, use slicing to extract the last three items in the list.
last = sports[-3:]
The len() function is also used in the code to increase its adaptability and ability to work with lists of any length.
last = sports[len(sports)-3:]
Finally, print the "last" variable to see the last three items in the list:
print(last)
The output will be ['track and field', 'curling', 'ping pong']
This program uses list slicing to extract the last three items in the list "sports" and assigns it to the variable "last".
The slice sports[-3:] will extract the last three items in the list, regardless of how many items are in the list. The program also uses the len() function to make the code more flexible and work for any list of any length.
To learn more about list from the given link.
https://brainly.in/question/6644883
#SPJ3