Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to extract the last x elements from a list [duplicate]

Tags:

python

If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list. How can I do this? I tried getting the difference between len(my_list) - 10 and use it as: new_list = [(len(my_list) - 10):] which does not work

Any suggestions? Thanks in advance

like image 487
sura Avatar asked Dec 19 '11 00:12

sura


People also ask

How do you find the last index of a duplicate element in a list Python?

So the index of last occurrence of an element in original list is equal to (length_of_list - index_in_reversed_list - 1). You can use the list. reverse() method to reverse the list and then find the index of first occurrence of the required element in reversed list by list. index() method.

How do you extract duplicates from a list in Python?

If you want to extract only duplicate elements from the original list, use collections. Counter() that returns collections. Counter (dictionary subclass) whose key is an element and whose value is its count. Since it is a subclass of a dictionary, you can retrieve keys and values with items() .

How do you slice the last 5 elements of a list in Python?

Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.

How do I get the last two items in a list Python?

Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.


2 Answers

it's just as simple as:

my_list[-10:] 

Additional Comment: (from the comments section)

If the initial list is less than 10 elements, then this solution will still work yielding the whole list. E.g. if my_list = [1,2,3], then my_list[-10:] is equal to [1,2,3]

like image 97
Felix Yan Avatar answered Oct 04 '22 18:10

Felix Yan


This shows how to chop a long list into a maximum size and put the rest in a new list. It's not exactly what you're asking about, but it may be what you really want:

>>> list1 = [10, 20, 30, 40, 50, 60, 70] >>> max_size = 5 >>> list2 = list1[max_size:] >>> list2 [60, 70] >>> list1 = list1[:max_size] >>> list1 [10, 20, 30, 40, 50] 

This is more like what you're asking about, basically the same, but taking the new list from the end:

>>> list1 = [10, 20, 30, 40, 50, 60, 70] >>> list2 = list1[:max_size] >>> list2 [10, 20, 30, 40, 50] >>> list2 = list1[-max_size:] >>> list2 [30, 40, 50, 60, 70] >>> list1 = list1[:-max_size] >>> list1 [10, 20] >>>  
like image 24
dkamins Avatar answered Oct 04 '22 20:10

dkamins