Concepts / Indexing and Slicing Strings

Indexing and Slicing Strings

For strings, the items are characters; for other collection types, the collection defines what counts as one item.

  • Programming
Interactive lab

Try it: Indexing and Slicing

How Python indexes a sequence from 0 (or from the end with negative numbers) and how a slice start:stop:step picks positions — with the exact CPython rules for omitted and out-of-range bounds.

How it works

  1. Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
  2. An index outside the string raises IndexError.
  3. A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
  4. A negative step walks backwards; a step of 0 is a ValueError.

Default run (7 steps): 'PYTHONIC'[1:6:2]: a slice copies characters from start up to (not including) stop, moving by step. … 'PYTHONIC'[1:6:2] → 'YHN' (positions 1, 3, 5).

Simplified: Works on a short string (up to 16 printable ASCII characters); lists slice by exactly the same rules.

Educational simulation

Loading the simulation…

The Hidden Count in a String

A string may look like one value, but it contains individual characters. The len() built-in function tells you how many items are in the value it receives. For a string, each character counts as one item, including letters, spaces, digits, and punctuation.

What do you think happens?

What should len('Hello world') return? Count every character, including the space.

Reveal answer
Answer:

11

The string contains H, e, l, l, o, a space, w, o, r, l, and d. The space is an item too, so the total is 11.

Characters and Positions

The count returned by len() also tells you how far the valid positions extend. Positions start at 0 rather than 1. Therefore, a string with length 11 has valid indices from 0 through 10. The final character is always at index length minus 1.

Hindex 0eindex 1lindex 2lindex 3oindex 4spaceindex 5windex 6oindex 7rindex 8lindex 9dindex 10nextnextnextnextnextnextnextnextnextnext
How do the characters in the string relate to their zero-based indices and the final valid position?
Key point

The number returned by len() is a count of items, not the final index. For a length of 11, the final index is 10.

Counting Every Character

H1 item11total itemse1 iteml1 iteml1 itemo1 itemspace1 itemw1 itemo1 itemr1 iteml1 itemd1 itemcounts towardcounts towardcounts towardcounts towardcounts towardcounts towardcounts towardcounts towardcounts towardcounts towardcounts toward
What exactly contributes to the result when len() counts Hello world?
Worked example

Finding the final valid position

The string Hello world has length 11. What is its final valid index?

  1. 1
    Start with the length

    The length is 11 because every character, including the space, is counted.

  2. 2
    Adjust for zero-based positions

    Positions begin at 0, so subtract 1 from the length to find the final valid index.

  3. 3
    Calculate

    11 minus 1 equals 10.

Result

The final valid index is 10.

Beyond Strings

len() is not limited to strings. It works with collection types such as lists, tuples, dictionaries, and sets. In each case, len() returns the number of items, but the meaning of item depends on the data type. For strings, the items are characters; for other collection types, the collection defines what counts as one item.

Collection typeWhat len() counts
StringCharacters, including spaces and punctuation
ListItems in the list
TupleItems in the tuple
DictionaryItems in the dictionary
SetItems in the set

The definition of an item varies by collection type.

Mistakes with Length and Indices

  • Common mistake

    Treating the length as the final index

    What it looks like

    A string has length 11, so its final index is assumed to be 11.

    Why it fails

    Indices start at 0, so a collection with 11 items uses indices 0 through 10.

    Do this instead

    Find the final index by subtracting 1 from the length.

  • Common mistake

    Ignoring spaces when counting a string

    What it looks like

    The space in Hello world is left out of the count.

    Why it fails

    len() counts every character in a string, including spaces.

    Do this instead

    Count letters, spaces, digits, and punctuation as individual characters.

  • Common mistake

    Assuming len() counts the same kind of item for every data type

    What it looks like

    The meaning of an item in a dictionary is assumed to be identical to the meaning of an item in a string.

    Why it fails

    len() works across collection types, but the definition of item varies by data type.

    Do this instead

    Identify what the particular collection treats as one item before interpreting the result.

Size-Based Practice

EASY

A string contains 7 characters, including one space. Determine the highest valid index. Then explain why the space must be included when determining the string's length.

Hints
  • Indices begin at 0.
  • The highest valid index is one less than the length.
  • Every character in a string contributes to len(), including spaces.
MEDIUM

Consider a collection whose type is not a string. Before interpreting its len() result, identify what that collection considers one item. Explain how this differs from counting characters in a string.

Hints
  • len() works with lists, tuples, dictionaries, and sets.
  • The meaning of item varies by data type.

Key Takeaways

  • len() returns the number of items in its argument as an integer.
  • For strings, every character counts, including spaces and punctuation.
  • Indices begin at 0, so the final valid index is always the length minus 1.
  • len() also works with lists, tuples, dictionaries, and sets, although the meaning of item varies by data type.

Related concepts

More concepts starting with I