Python list all but last element

6 ways to get the last element of a list in Python

In this article, we will discuss six different ways to get the last element of a list in python.

Get last item of a list using negative indexing

List in python supports negative indexing. So, if we have a list of size “S”, then to access the Nth element from last we can use the index “-N”. Let’s understand by an example,
Suppose we have a list of size 10,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

To access the last element i.e. element at index 9 we can use the index -1,

# Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem)

Similarly, to access the second last element i.e. at index 8 we can use the index -2.

Frequently Asked:

Using negative indexing, you can select elements from the end of list, it is a very efficient solution even if you list is of very large size. Also, this is the most simplest and most used solution to get the last element of list. Let’s discuss some other ways,

Get last item of a list using list.pop()

In python, list class provides a function pop(),

It accepts an optional argument i.e. an index position and removes the item at the given index position and returns that. Whereas, if no argument is provided in the pop() function, then the default value of index is considered as -1. It means if the pop() function is called without any argument then it removes the last item of list and returns that.

Let’s use this to remove and get the last item of the list,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem)

The main difference between this approach and previous one is that, in addition to returning the last element of list, it also removes that from the list.

Get last item of a list by slicing

We can slice the end of list and then select first item from it,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get a Slice of list, that contains only last item and select that item last_elem = sample_list[-1:][0] print('Last Element: ', last_elem)

We created a slice of list that contains only the last item of list and then we selected the first item from that sliced list. It gives us the last item of list. Although it is the most inefficient approach, it is always good to know different options.

Get last item of a list using itemgetter

Python’s operator module provides a function,

Читайте также:  Java csv file to string

It returns a callable object that fetches items from its operand using the operand’s __getitem__() method. Let’s use this to get the last item of list by passing list as an operand and index position -1 as item to be fetched.

import operator sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem)

It gives us the last item of list.

Get last item of a list through Reverse Iterator

In this solution we are going to use two built-in functions,

  1. reversed() function : It accepts a sequence and returns a Reverse Iterator of that sequence.
  2. next() function: It accepts an iterator and returns the next item from the iterator.

So, let’s use both the reversed() and next() function to get the last item of a list,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem)

It gives us the last item of list.
How did it work?
By calling the reversed() function we got a Reverse Iterator and then we passed this Reverse Iterator to the next() function. Which returned the next item from the iterator.
As it was a Reverse Iterator of our list sequence, so it returned the first item in reverse order i.e. last element of the list.

Get last item of a list by indexing

As the indexing in a list starts from 0th index. So, if our list is of size S, then we can get the last element of list by selecting item at index position S-1.
Let’s understand this by an example,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem)

It gives us the last item of list.

Using the len() function we got the size of the list and then by selecting the item at index position size-1, we fetched the last item of the list.

So, here we discussed 6 different ways to fetch the last element of a list, although first solution is the simplest, efficient and most used solution. But it is always good to know other options, it gives you exposure to different features of language. It might be possible that in future, you might encounter any situation where you need to use something else, like in 2nd example we deleted the last element too after fetching its value.

The Complete example is as follows,

import operator def main(): print('*** Get last item of a list using negative indexing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem) print('*** Get last item of a list using list.pop() ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem) print('*** Get last item of a list by slicing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = sample_list[-1:][0] print('Last Element: ', last_elem) print('*** Get last item of a list using itemgetter ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem) print('*** Get last item of a list through Reverse Iterator ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem) print("*** Get last item of a list by indexing ***") sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem) if __name__ == '__main__': main()
*** Get last item of a list using negative indexing *** Last Element: 9 *** Get last item of a list using list.pop() *** Last Element: 9 *** Get last item of a list by slicing *** Last Element: 9 *** Get last item of a list using itemgetter *** Last Element: 9 *** Get last item of a list through Reverse Iterator *** Last Element: 9 *** Get last item of a list by indexing *** Last Element: 9

Источник

Читайте также:  Java runtime environment is missing or corrupted

Python get all but last element of list

Solution 2: If you are certain the will always be last, slicing is an option whereby you trim off the last element from every sub-list in with ( means grab all except the last element): Alternatively, you can do this by iterating through the elements of , iterating through each sub-element and evaluating if it is an instance of a , i.e: This filters out any element the list which is a sub-list in that isn’t an instance of the type. If you need to compare the last value to some special value, chain that value to the end Solution 1: You can get the last element of each element with the index and just do it for all the sub lists.

How to loop through all but the last item of a list?

If y is a generator, then the above will not work.

the easiest way to compare the sequence item with the following:

for i, j in zip(a, a[1:]): # compare i (the current) to j (the following) 

If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).

from itertools import tee, izip, chain def pairwise(seq): a,b = tee(seq) b.next() return izip(a,b) for current_item, next_item in pairwise(y): if compare(current_item, next_item): # do what you have to do 

If you need to compare the last value to some special value, chain that value to the end

for current, next_item in pairwise(chain(y, [None])): 

Python — How to extract the last x elements from a list, @hop ­— Yes, there is. If his list is length 9, for example, the index would turn into -1, which would only give him a one-element slice from the end of …

Python — get the last element of each list in a list of lists

You can get the last element of each element with the index -1 and just do it for all the sub lists.

print [item[-1] for item in my_list] # ['b1', 'b2', 'c3', 'e4'] 

If you are looking for idiomatic way, then you can do

import operator get_last_item = operator.itemgetter(-1) print map(get_last_item, my_list) # ['b1', 'b2', 'c3', 'e4'] print [get_last_item(sub_list) for sub_list in my_list] # ['b1', 'b2', 'c3', 'e4'] 

If you are using Python 3.x, then you can do this also

print([last for *_, last in my_list]) # ['b1', 'b2', 'c3', 'e4'] 
last_items = map(lambda x: x[-1], my_list) 
from operator import itemgetter print map(itemgetter(-1), my_list) 
>>> [i.pop() for i in my_list] ['b1', 'b2', 'c3', 'e4'] 
>>> my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']] >>> [i[-1] for i in my_list] ['b1', 'b2', 'c3', 'e4'] 

Python — How to obtain the last index of a list?, The best and fast way to obtain the content of the last index of a list is using -1 for number of index , for example: my_list = [0, 1, ‘test’, 2, ‘hi’] print …

Читайте также:  Dynamic objects in java

In a list of lists how to get all the items except the last one for each list?

This is the shortest and easiest way:

It is called a list comprehension .

If you are certain the int will always be last, slicing is an option whereby you trim off the last element from every sub-list sub in x with sub[:-1] ( [:-1] means grab all except the last element):

out = [sub[:-1] for sub in x] # or sub[:2] if sub is always 3 elements long print(out) [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] 

Alternatively, you can do this by iterating through the elements of x , iterating through each sub-element and evaluating if it is an instance of a float , i.e:

out = [[i for i in sub if isinstance(i, float)] for sub in x] 

This filters out any element the list sub which is a sub-list in x that isn’t an instance of the float type. This operates irregardless of positioning so you could use it if the position of the int isn’t always last:

print(out) [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] 

Finally, for an in-place approach, for looping and pop ing is a viable option:

print(x) [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]] 

Slice — How do I extract the last two items from the list, If n is the total number of values the last two item can be sliced as: [n-1:] How can I put down in the code? python slice. Share. Improve this question . …

Python — Go through list without last element

You can simply use slice notation to skip the last element:

for i, (a, b) in enumerate(list_of_tuples[:-1]): 
>>> lst = [1, 2, 3, 4, 5] >>> lst[:-1] [1, 2, 3, 4] >>> for i in lst[:-1]: . i . 1 2 3 4 >>> 

Python how to check if last element in for loop?, 4 Answers. In your scenario you are using enumerate and you want to break at last element of for so you can check the index returned by enumerate …

Источник

Python – Traverse List except Last Element

To traverse Python List except for the last element, there are two ways.

  • Get a copy of the list without last element and traverse this list using a looping statement.
  • Use index and length of list to traverse the list until the last element, but not executing the loop for the last element.

In this tutorial, we will go through examples for these two approaches.

Examples

1. Traverse List except last element using Slicing

In this example, we will use the first approach that we mentioned above.

We can use slicing to get the list without last element, and then use for loop or while loop to traverse the elements.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9] for x in source_list[:-1]: print(x)

We have traversed the list except for the last element.

2. Traverse List except last element using index

In this example, we will use the second approach that we mentioned during introduction.

We can use index to access Python List elements, and use while loop to traverse through them. To traverse through list except for the last element, we have to check the condition if the index is less than the list length by one, and stop traversing when the condition fails.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9] index = 0 while index < len(source_list) - 1: print(source_list[index]) index += 1

Summary

In this tutorial of Python Examples, we learned how to traverse through Python List except for the last element, using slicing and index.

Источник

Оцените статью