A list, NList contains following record as list elements:
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the city and country, which are not in India and distance is less than 3500 km from Delhi.
Answer by student:
Detailed answer by teachoo:
- The question asks us to write a user defined function in Python to perform the specified operations on the stack named travel, which is a list that can be manipulated using the append() method. The append() method adds an element to the end of the list.
- The function takes a nested list as an argument, which contains records as list elements. Each record is a list of three items: city, country, and distance from Delhi.
- The function should push a list object containing name of the city and country, which are not in India and distance is less than 3500 km from Delhi, to the travel stack.
- To do this, we need to use the following steps:
- Define the function using the def keyword, followed by the function name and parentheses. In this case, we name the function Push_element and use NList as the parameter.
- Loop through each record in the NList using a for loop. We can access each element of a list using indexing or slicing.
- Assign the values of city, country, and distance from each record to separate variables using multiple assignment. This means that we can assign values to multiple variables in one line by separating them with commas. For example, city, country, distance = record will assign the first item of record to city, the second item to country, and the third item to distance.
- Check if the country is not India and the distance is less than 3500 using the != operator, which checks for inequality, and the < operator, which checks for less than. We also use the and operator to combine multiple conditions. For example, country != “India” and distance < 3500 will return True if both conditions are True, or False otherwise.
- If the condition is True, push a list object containing city and country to the travel stack using the append() method. For example, travel.append([city, country]) will add [city, country] to the end of the travel list.
- End the function definition with proper indentation.
So, the correct answer is: