1. Home
  2. Blog
  3. Software Development

Software Development

Python Slicing Explained: Start, Stop and Step With Examples

Python slicing pulls out part of a list, string or tuple with one short expression. Learn how start, stop and step work, why negative indexes count from the end, how to reverse and copy, and how slice assignment changes a list in place, with every output tested.

9 min read
Python slicing explained: start, stop and step with examples

Key takeaways

  • Python slicing uses seq[start:stop:step]. The start is included, the stop is not.
  • Negative numbers count from the end, so nums[-3:] gives the last three items.
  • [::-1] reverses a sequence, and [:] makes a shallow copy.
  • Slices never raise IndexError. Out-of-range bounds are clipped quietly, which can hide bugs.

Almost every Python program cuts lists and strings into pieces: the first ten rows of a file, the last three log lines, every second item, a reversed name. Python slicing does all of that with one compact expression, and once the rules click you will use it every day.

Every example below was run on Python 3.13.6 and the output is shown exactly as printed. If you are new to the language, our Python tutorial for beginners covers lists and strings first.

What is slicing in Python?

Slicing is a way to read (or replace) a range of items from any sequence: a list, string, tuple, range, bytes or bytearray. Indexing with nums[2] returns one item. Slicing with nums[2:5] returns a new sequence of the same type containing several items. A list slice is a new list, a string slice is a new string and a tuple slice is a new tuple.

Because a slice is a new object, reading a slice never changes the original. Writing to a slice, which we cover later, is the one way slicing modifies a list in place.

Python slicing syntax: start, stop, step

The full form has three parts separated by colons:

sequence[start:stop:step]
  • start: the index of the first item to include. Default: the beginning.
  • stop: the index where the slice ends. That item is not included. Default: the end.
  • step: how far to jump between items. Default: 1. It can be negative, but never 0.

Every part is optional. These are the shapes you will see most:

nums = [10, 20, 30, 40, 50, 60, 70, 80]

print(nums[2:5])   # [30, 40, 50]
print(nums[:3])    # [10, 20, 30]
print(nums[5:])    # [60, 70, 80]
print(nums[::2])   # [10, 30, 50, 70]
print(nums[1::2])  # [20, 40, 60, 80]

A handy check: for positive start and stop, the slice length is stop - start. nums[2:5] has 5 – 2 = 3 items. That half-open design is why nums[:3] and nums[3:] split a list cleanly with no overlap and no gap.

How slice indexes work

The easiest mental model is to picture indexes as the gaps between items, not the items themselves:

 +----+----+----+----+----+----+----+----+
 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 |
 +----+----+----+----+----+----+----+----+
 0    1    2    3    4    5    6    7    8
-8   -7   -6   -5   -4   -3   -2   -1

A slice [2:5] cuts at gap 2 and gap 5 and keeps whatever sits between them: 30, 40 and 50. Seen this way, [5:] is everything after gap 5, and [:3] is everything before gap 3. The negative row underneath is the subject of the next section.

Negative indexes in slices

A negative index counts from the end: -1 is the last item, -2 the one before. Python converts a negative index by adding the length, so on our 8-item list, -3 becomes 5.

print(nums[-3:])   # [60, 70, 80]   last three
print(nums[:-2])   # [10, 20, 30, 40, 50, 60]   all but last two
print(nums[-5:-2]) # [40, 50, 60]

This is perfect for log files and queues: lines[-10:] always gives the last ten lines, whatever the file length, and items[:-1] drops a trailing item such as an empty string after a split.

Using a step value

The third number sets the stride. A step of 2 takes every second item, 3 every third, and so on. Combine it with a start to choose the offset:

print(nums[::2])   # [10, 30, 50, 70]   even positions
print(nums[1::2])  # [20, 40, 60, 80]   odd positions
print(nums[::3])   # [10, 40, 70]

A step of 0 is not allowed and raises ValueError: slice step cannot be zero. Splitting a list into two interleaved halves with [::2] and [1::2] is a common trick for pairing data, often followed by Python zip to walk both halves together.

Reversing with a negative step

With a negative step, the slice walks backwards, so the defaults flip: start defaults to the last item and stop to before the first. That is why [::-1] reverses any sequence:

print(nums[::-1])    # [80, 70, 60, 50, 40, 30, 20, 10]
print(nums[5:1:-1])  # [60, 50, 40, 30]
print(nums[1:5:-1])  # []

s = "stackquora"
print(s[::-1])                       # arouqkcats
print("racecar" == "racecar"[::-1])  # True

The third line surprises people. With a negative step, start must be to the right of stop. [1:5:-1] asks Python to walk backwards from 1 to 5, which is impossible, so you get an empty list rather than an error. When a reversed slice comes back empty, swap start and stop.

Out-of-range slices never raise errors

Indexing past the end raises an exception. Slicing past the end does not:

print(nums[2:100])  # [30, 40, 50, 60, 70, 80]
print(nums[100:])   # []
nums[100]           # IndexError: list index out of range

Python clips slice bounds to the valid range. This is convenient, since text[:280] is safe for short and long strings alike, but it can also hide a bug. If your code expects exactly five items from row[3:8] and the row is short, you silently get fewer. When the length matters, check it with len() or an assertion.

Tip: in tests, assert the length of important slices. A silent short slice is a classic source of off-by-one bugs that only show up with real data.

Slicing strings and tuples

Strings and tuples slice exactly like lists, and the result keeps the same type:

s = "stackquora"
print(s[:5], s[-5:])       # stack quora

t = (1, 2, 3, 4)
print(t[1:3])              # (2, 3)
print(range(0, 20)[::5])   # range(0, 20, 5)

Note the last line: slicing a range returns another lazy range, not a list, so it costs almost nothing even for huge ranges. Strings are immutable, so you can read slices but never assign to them. To change part of a string, build a new one, for example s[:5] + "-" + s[5:]. For other text jobs, see our guide to Python string methods.

Copying a list with [:]

An empty slice [:] copies the whole list. The copy is a new list object, but it is shallow: nested objects are shared, not duplicated.

grid = [[1, 2], [3, 4]]
copy = grid[:]
copy[0].append(99)
print(grid)          # [[1, 2, 99], [3, 4]]
print(copy is grid)  # False

The outer list is new, but copy[0] and grid[0] are the same inner list, so appending through the copy changed the original. For nested data you need copy.deepcopy(), explained in our Python deepcopy guide. For flat lists, nums[:], nums.copy() and list(nums) all do the same job.

Slice assignment and deletion

On a mutable list, a slice can appear on the left of =. The selected range is replaced by the items on the right, and the list can grow or shrink:

a = nums[:]
a[1:3] = [99]       # replace two items with one
print(a)            # [10, 99, 40, 50, 60, 70, 80]

b = nums[:]
b[1:1] = [11, 12]   # empty slice = insert
print(b)            # [10, 11, 12, 20, 30, 40, 50, 60, 70, 80]

c = nums[:]
del c[::2]          # delete every second item
print(c)            # [20, 40, 60, 80]

Extended slices (those with a step) are stricter. The replacement must have exactly the same length:

d = nums[:]
d[::2] = [1, 2]
# ValueError: attempt to assign sequence of size 2 to extended slice of size 4

The slice() object

Behind the colon syntax is a built-in slice object. You can create one, name it and reuse it, which makes fixed-width parsing much easier to read:

first_three = slice(0, 3)
print(nums[first_three])               # [10, 20, 30]
print(first_three.indices(len(nums)))  # (0, 3, 1)
print(slice(-3, None).indices(8))      # (5, 8, 1)

The indices() method shows the real start, stop and step Python will use for a given length, which is a great way to debug a confusing negative slice. A named slice such as PRICE = slice(20, 28) also documents what each column of a fixed-width record means.

Slicing generators and iterators

Generators are not sequences, so the colon syntax fails:

(x for x in range(5))[1:3]
# TypeError: 'generator' object is not subscriptable

import itertools
squares = (x * x for x in range(10**9))
print(list(itertools.islice(squares, 3, 7)))  # [9, 16, 25, 36]

itertools.islice takes start, stop and step like a slice but works lazily, so it read only the first seven values of a billion-item generator. It does not accept negative values. Our Python itertools guide shows more lazy tools.

How fast is slicing?

A slice copies references into a new list, so it costs time and memory in proportion to the slice length. We timed operations on a one-million-item list (best of three runs, 20 calls each):

Operation Time per call
big[::-1] 8.78 ms
list(reversed(big)) 9.25 ms
big[:] 8.80 ms
big.copy() 8.61 ms

All four are effectively the same speed, so choose the most readable one. The real cost to watch is slicing inside a loop: for i in range(n): process(data[i:]) copies the tail every time and turns a linear job quadratic. Pass indexes instead, or use islice or enumerate.

Common Python slicing mistakes

  • Expecting the stop item. nums[0:3] returns three items, indexes 0, 1 and 2. The stop is exclusive.
  • Wrong order with a negative step. nums[1:5:-1] is empty. With a negative step, start must be larger than stop.
  • Trusting a slice length. Slices clip silently, so a short input gives a short slice without any error.
  • Assuming a deep copy. [:] copies only the outer list. Nested lists and dicts are shared.
  • Slicing in a hot loop. Each slice is a new copy; repeated slicing of large lists wastes time and memory.
  • Using colon syntax on generators. Use itertools.islice instead.

Python slicing cheat sheet

Expression Result
a[i:j] Items from i up to, not including, j
a[:n] First n items
a[-n:] Last n items
a[:-n] All but the last n
a[::2] Every second item
a[::-1] Reversed copy
a[:] Shallow copy
a[i:i] = x Insert x at position i
del a[i:j] Remove a range

Final thoughts

Python slicing comes down to three numbers and two rules: start is included, stop is not, and negative values count from the end. Add the step for strides and reversal, remember that slices are shallow copies that never raise on bad bounds, and you can handle almost any list or string extraction in one readable line. When slicing is not enough, a list comprehension can filter and transform in the same pass.

Frequently asked questions

What does [::-1] mean in Python?

It is a slice with default start and stop and a step of minus one, so it walks the whole sequence backwards and returns a reversed copy of a list, string or tuple.

Is the stop index included in a Python slice?

No. The start index is included and the stop index is excluded, so nums[2:5] returns the items at indexes 2, 3 and 4.

Why does my slice return an empty list?

Usually the start is past the end of the list, or you used a negative step with start smaller than stop. With a negative step, start must be to the right of stop.

Does slicing copy a list in Python?

Yes, slicing a list returns a new list, but the copy is shallow. Nested lists or dictionaries inside it are shared with the original, so use copy.deepcopy for nested data.

Can you slice a dictionary or a set?

No. Dictionaries and sets are not sequences. Convert the keys or items to a list first, or use itertools.islice to take the first few entries without building a full list.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Software Development

Python Random Module: randint, choice, seed and More

The Python random module explained: randint, randrange, choice, choices, sample, shuffle, seed, weights and when to use secrets instead, with…

Read article →
Software Development

Python Slicing Explained: Start, Stop and Step With Examples

Python slicing explained with start, stop and step, negative indexes, reversing, copying and slice assignment, with tested examples and a…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →