Python - Get sum of last K list items using slice


In Python, the slice method allows us to extract specific elements from a sequence, such as strings, lists, or tuples. It provides a concise and flexible way to work with subsequences within a larger sequence. In this article, we will explore how to obtain the sum of the last K items in a list using slice operations.

Algorithm

To find the sum of the last K items in a list, we can follow a simple algorithm:

  • Accept the list and the value of K as inputs.

  • Use the slice operator to extract the last K items from the list.

  • Calculate the sum of the extracted items.

  • Return the sum as the output.

Syntax

sequence[start:end:step]

Here, the slice method takes three optional parameters:

  • start (optional): The index of the element where the slice should start. If not provided, it defaults to the beginning of the sequence.

  • end (optional): The index of the element where the slice should end (exclusive). If not provided, it defaults to the end of the sequence.

  • step (optional): The step or increment value for selecting elements. If not provided, it defaults to 1.

The start, end and step values can be positive or negative integers, allowing you to traverse the sequence in both forward and backward directions.

Example 1: Sum of Last K items using Slice method

By specifying a negative index in the slice, we can start from the end of the list and go backward. The following is the syntax for obtaining the sum of the last K list items using slice:

In the below example, we have a list my_list containing 10 elements. We want to find the sum of the last 4 items in the list. By using the slice operator [-K:], we specify the range from the fourth−to−last element to the end of the list. The sum() function then calculates the sum of the extracted elements, resulting in 280.

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
K = 4
sum_of_last_k = sum(my_list[-K:])
print("Sum of last", K, "items:", sum_of_last_k)

Output

Sum of last 4 items: 340

Example 2: Using tail function from the collection module

The tail function from the collections module is a convenient method for extracting the last N elements from a sequence. It allows you to avoid the need for slicing with negative indices.

In the below example, we import the deque class from the collections module and specify the desired maximum length (maxlen) as N. By passing the numbers list and maxlen=N to deque, we create a deque object that retains only the last N elements. Converting the deque object to a list using list(tail_elements) allows us to obtain the tail elements [6, 7, 8, 9, 10].

from collections import deque

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
N = 5
tail_elements = deque(numbers, maxlen=N)
print(list(tail_elements))

Output

[6, 7, 8, 9, 10]

Example 3: Using the islice function from the itertools module

The islice function from the itertools module allows you to extract a specific subsequence from an iterable, such as a list or string, by providing the start, stop, and step values.

In the below example, we import the islice function from the itertools module. By passing the numbers list along with the start, stop, and step values to islice(numbers, start, stop, step), we extract the desired subsequence [6, 8, 10]. Converting the result to a list using list(islice(...)) enables us to print the subsequence

from itertools import islice

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
start = 5
stop = 10
step = 2
subsequence = list(islice(numbers, start, stop, step))
print(subsequence)

Output

[6, 8, 10]

Conclusion

In this article, we discussed how we can get sum of the last k items using the slice method. The slice method provides a concise and efficient way to perform such calculations and makes the task of taking the sum of the last K items of the list an easy task. The slice method can be used for other purposes also as Extracting a Subsequence, Skipping Elements with Step Value, Reversing a Sequence, Getting the Last K Elements, etc.

Updated on: 18-Jul-2023

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements