Table of Contents
algorithm
grammar
Example 1: Use the slicing method to find the sum of the last K items
Output
Example 2: Using the tail function in the collection module
Example 3: Using the islice function from the itertools module
Conclusion
Home Backend Development Python Tutorial Python - Get sum of last K list items using slicing

Python - Get sum of last K list items using slicing

Sep 06, 2023 am 11:17 AM

Python - 使用切片获取最后K个列表项的总和

In Python, the slicing method allows us to extract specific elements from a sequence such as a string, list, or tuple. It provides a concise and flexible way to handle subsequences within larger sequences. In this article, we will explore how to get the sum of the last K elements in a list using slicing operations.

algorithm

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

  • Accepts a list and the value of K as input.

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

  • Calculate the sum of extracted items.

  • Return the sum as the output.

grammar

sequence[start:end:step]
Copy after login

Here, the slice method accepts 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 (exclusive) of the element at which the slice should end. If not provided, 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: Use the slicing method to find the sum of the last K items

By specifying negative indexes in the slice, we can traverse backward starting from the end of the list. Here is the syntax for using slicing to get the sum of the last K list items:

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)
Copy after login

Output

Sum of last 4 items: 340
Copy after login

Example 2: Using the tail function in the collection module

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

In the following example, we import the deque class from the collections module and specify the required maximum length (maxlen) as N. By passing the numbers list and maxlen=N to deque, we create a deque object that holds only the last N elements. Use list(tail_elements) to convert the deque object into a list, and you can get 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))
Copy after login

Output

[6, 7, 8, 9, 10]
Copy after login

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)
Copy after login

Output

[6, 8, 10]
Copy after login

Conclusion

In this article, we discussed how to use the slicing method to get the sum of the last k items. The slicing method provides a concise and efficient way to perform such calculations and makes it easy to get the sum of the last k items of the list. The slicing method can also be used for other purposes like extracting subsequences, skipping elements with step values, reversing sequences, getting the last k elements, etc.

The above is the detailed content of Python - Get sum of last K list items using slicing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: The Power of Versatile Programming Python: The Power of Versatile Programming Apr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

See all articles