Python Slicing · Examples
Beginner

Python Slicing Examples

Short, runnable programs that show python slicing in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Slicing lesson.

1Splitting a list into batches

Step through the list in jumps of size with range(), and take one slice per jump. The last batch is allowed to be shorter, because a slice that runs past the end simply stops.

Splitting a list into batches
orders = [f"order-{n}" for n in range(1, 11)]
size = 4
for start in range(0, len(orders), size):
    batch = orders[start:start + size]
    print("Batch", start // size + 1, batch)
Expected outputBatch 1 ['order-1', 'order-2', 'order-3', 'order-4']
Batch 2 ['order-5', 'order-6', 'order-7', 'order-8']
Batch 3 ['order-9', 'order-10']

2A moving average with a sliding window

Slice a window of window readings at every position and average it. Smoothing noisy data this way is a daily job in analytics.

A moving average with a sliding window
daily = [12, 15, 11, 18, 20, 17, 25]
window = 3
for i in range(len(daily) - window + 1):
    part = daily[i:i + window]
    print(part, "average", round(sum(part) / window, 1))
Expected output[12, 15, 11] average 12.7
[15, 11, 18] average 14.7
[11, 18, 20] average 16.3
[18, 20, 17] average 18.3
[20, 17, 25] average 20.7

3Reading fixed-width text with named slices

Give each field a slice object once, then reuse them on every line. The None at the end of MESSAGE means "to the end", just like leaving the stop out.

Reading fixed-width text with named slices
DATE = slice(0, 10)
TIME = slice(11, 19)
LEVEL = slice(20, 25)
MESSAGE = slice(26, None)

line = "2025-03-14 09:30:05 ERROR disk full on node 3"
print("Date:", line[DATE])
print("Time:", line[TIME])
print("Level:", line[LEVEL])
print("Message:", line[MESSAGE])
Expected outputDate: 2025-03-14
Time: 09:30:05
Level: ERROR
Message: disk full on node 3

4Editing a playlist with slice assignment

A slice on the left of = replaces that part of the list. An empty slice inserts, del removes, and assigning an empty list deletes the section.

Editing a playlist with slice assignment
playlist = ["intro", "song A", "song B", "song C", "outro"]
playlist[1:4] = ["song X", "song Y"]
print(playlist)
playlist[1:1] = ["jingle"]
print(playlist)
del playlist[:1]
print(playlist)
playlist[-1:] = []
print(playlist)
Expected output['intro', 'song X', 'song Y', 'outro']
['intro', 'jingle', 'song X', 'song Y', 'outro']
['jingle', 'song X', 'song Y', 'outro']
['jingle', 'song X', 'song Y']

5Separating interleaved sensor readings

When two kinds of values alternate, [0::2] collects the ones at even positions and [1::2] the ones at odd positions.

Separating interleaved sensor readings
readings = [21.5, 40, 22.0, 42, 23.5, 45, 24.0, 44]
temps = readings[0::2]
humidity = readings[1::2]
print("Temperatures:", temps)
print("Humidity:", humidity)
print("Latest:", temps[-1], humidity[-1])
Expected outputTemperatures: [21.5, 22.0, 23.5, 24.0]
Humidity: [40, 42, 45, 44]
Latest: 24.0 44

6Masking and shortening text

Slices on strings are perfect for showing only the end of a card number, dropping a fixed prefix or cutting a long title down for a preview.

Masking and shortening text
card = "4111111111111111"
print("*" * (len(card) - 4) + card[-4:])

code = "ID-20931"
print(code[3:])
print(int(code[3:]) + 1)

title = "Python slicing explained in detail"
print(title[:20] + "...")
Expected output************1111
20931
20932
Python slicing expla...

Practise next

Python Slicing exercises → Back to the lesson

Python Strings examplesPython Lists examplesPython List Methods examplesPython Tuples examples