
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get First and Last Elements of a List in Python
There may be situation when you need to get the first and last element of the list. The tricky part here is you have to keep track of the length of the list while finding out these elements from the lists. Below are the approaches which we can use to achieve this. But of course all the approaches involve using the index of the elements in the list.
Using only index
In any list the first element is assigned index value 0 and the last element can be considered as a value -1. So we apply these index values to the list directly and get the desired result.
Example
Alist = ['Sun','Mon','Tue','Wed','Thu'] print("The given list : ",Alist) print("The first element of the list : ",Alist[0]) print("The last element of the list : ",Alist[-1])
Output
Running the above code gives us the following result −
The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] The first element of the list : Sun The last element of the list : Thu
List slicing
List slicing is another method in which we directly refer to the positions of elements using the slicing technique using colons. The first element is accessed by using blank value before the first colon and the last element is accessed by specifying the len() with -1 as the input.
Example
Alist = ['Sun','Mon','Tue','Wed','Thu'] print("The given list : ",Alist) first_last = Alist[::len(Alist)-1] print(first_last)
Output
Running the above code gives us the following result −
The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] ['Sun', 'Thu']
Using For loop
We can also use a for loop with in operator giving the index values as 0 and -1.
Example
Alist = ['Sun','Mon','Tue','Wed','Thu'] print("The given list : ",Alist) first_last = [Alist[n] for n in (0,-1)] print(first_last)
Output
Running the above code gives us the following result −
The given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] ['Sun', 'Thu']