Python Language Indexing and Slicing

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • obj[start:stop:step]
  • slice(stop)
  • slice(start, stop[, step])

Parameters

ParamerDescription
objThe object that you want to extract a "sub-object" from
startThe index of obj that you want the sub-object to start from (keep in mind that Python is zero-indexed, meaning that the first item of obj has an index of 0). If omitted, defaults to 0.
stopThe (non-inclusive) index of obj that you want the sub-object to end at. If omitted, defaults to len(obj).
stepAllows you to select only every step item. If omitted, defaults to 1.

Remarks

You can unify the concept of slicing strings with that of slicing other sequences by viewing strings as an immutable collection of characters, with the caveat that a unicode character is represented by a string of length 1.

In mathematical notation you can consider slicing to use a half-open interval of [start, end), that is to say that the start is included but the end is not. The half-open nature of the interval has the advantage that len(x[:n]) = n where len(x) > =n, while the interval being closed at the start has the advantage that x[n:n+1] = [x[n]] where x is a list with len(x) >= n, thus keeping consistency between indexing and slicing notation.



Got any Python Language Question?