List is a collection of items which are arranged in ordered manner. We can access each element of a list using index number. Each element in a list has an index number. This index number starts with 0. First element in a list will have index number 0, second element will have index number 1 and so on.
Below is the example of country list with elements.
country = [‘India’,’USA’,”Russia’,’England’,’Norway’]
There are 5 elements in above list. First element in a list is India with index number 0, second element is USA with index number 1, third element is Russia with index number 2, fourth element is England with index number 3 and fifth element is Norway with index number 4
Elements India USA Russia England Norway
Index Number 0 1 2 3 4
Below is the logic to display last element from a list
- Create a list.
- Calculate total length of a list using len() function.
- Subtract 1 from total length of a list to get index number of last element.
Creating city list
city = ['Mumbai','Bangalore','Delhi','Hyderabad','Chennai','Pune','Kolkatta']
Displaying all elements from a list
print('Complete List:%s'%city)
Finding number of elements in a list using len() function.
l =len(city)
Displaying total length or number of elements in a list.
print('Number of elements in city list:%s'%l)
Minus 1 from variable l which has total length of a list and assigning result to variable last_element.
last_element = l - 1
Display last element. Variable last_element contain index position of last element.
print('Last element in a list:%s'%city[last_element])
OUTPUT
Complete List:['Mumbai', 'Bangalore', 'Delhi', 'Hyderabad', 'Chennai', 'Pune', 'Kolkatta']
Number of elements in city list:7
Last element in a list:Kolkatta
Complete Code
city = ['Mumbai','Bangalore','Delhi','Hyderabad','Chennai','Pune','Kolkatta'] print('Complete List:%s'%city) l =len(city) print('Number of elements in city list:%s'%l) last_element = l - 1 print('Last element in a list:%s'%city[last_element])