Python - K Elements Reversed Slice

K Elements Reversed Slice extracts the last K elements from a list and returns them in reverse order. This technique is useful for data analysis, queue processing, and extracting recent entries from datasets.

What is K Elements Reversed Slice?

A K elements reversed slice takes the last K elements from a list and reverses their order. For example, if we have [1, 2, 3, 4, 5] and K=3, we get the last 3 elements [3, 4, 5] reversed as [5, 4, 3].

Using Slicing

The most concise approach uses Python's slice notation with negative indexing and step ?

def rev_slice(input_list, k):
    return input_list[-k:][::-1]

test_list = [2, 4, 20, 40, 60, 80]
k = 3
result = rev_slice(test_list, k)
print("K elements reversed slice:", result)
K elements reversed slice: [80, 60, 40]

Using reversed() Function

The reversed() function creates an iterator that traverses elements in reverse order ?

def rev_slice(input_list, k):
    return list(reversed(input_list[-k:]))

test_list = [1, 2, 3, 4, 5]
k = 2
result = rev_slice(test_list, k)
print("K elements reversed:", result)
K elements reversed: [5, 4]

Using List Comprehension

List comprehension with range() provides explicit control over index selection ?

def rev_slice(input_list, k):
    return [input_list[i] for i in range(len(input_list) - k, len(input_list))][::-1]

test_list = [10, 20, 30, 40, 50]
k = 3
result = rev_slice(test_list, k)
print("K elements reversed:", result)
K elements reversed: [50, 40, 30]

Using range() with append()

This method builds the result iteratively using a loop and append() ?

def rev_slice(input_list, k):
    reversed_slice = []
    for i in range(len(input_list) - 1, len(input_list) - k - 1, -1):
        reversed_slice.append(input_list[i])
    return reversed_slice

test_list = [100, 200, 300, 400, 500, 600]
k = 4
result = rev_slice(test_list, k)
print("K elements reversed:", result)
K elements reversed: [600, 500, 400, 300]

Comparison

Method Performance Readability Best For
Slicing [-k:][::-1] Fastest High General use
reversed() Fast High Memory efficiency
List comprehension Moderate Medium Complex conditions
range() + append() Slowest Low Learning purposes

Practical Example

Getting the last 3 scores in reverse order for a leaderboard ?

scores = [85, 92, 78, 96, 88, 94, 99]
recent_scores = scores[-3:][::-1]
print("Recent 3 scores (newest first):", recent_scores)
Recent 3 scores (newest first): [99, 94, 88]

Conclusion

K elements reversed slice is commonly used for extracting recent data in reverse chronological order. The slicing method [-k:][::-1] is the most efficient and readable approach for this operation.

Updated on: 2026-03-27T12:45:17+05:30

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements