Was it helpful?

Question


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

 Live Demo

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

 Live Demo

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

 Live Demo

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']
raja
Published on 09-Sep-2020 12:25:22

Was it helpful?
Not affiliated with Tutorialspoint
scroll top