Concepts / Modifying Sequences

Modifying Sequences

Membership tests (in and not in) check if an item exists anywhere in a sequence.

  • Programming

Three Ways to Work with Sequences

Lists, tuples, and strings are sequences: ordered collections whose contents can be examined in several consistent ways. Membership tests ask whether something exists, indexing retrieves one item at a position, and slicing retrieves a portion of the sequence. These operations let you work with sequence contents without treating every sequence type as a completely different tool.

Key point

Keep the three questions separate: Does this item exist? Which item is at this position? Which portion should I extract?

Checking for Membership

The membership operators in and not in check whether an item exists anywhere in a sequence. The expression item in sequence asks whether the item occurs in the sequence. The expression item not in sequence asks whether it does not occur. The result is a Boolean answer: either true or false.

itemitem in sequence?TruesequenceFalsechecksearchfoundnot found
How does a membership test determine whether an item exists anywhere in a sequence?
Worked example

Testing a List and a String

Determine what these membership tests ask about the sequences ["red", "green", "blue"] and "python".

  1. 1
    List membership

    The expression "green" in ["red", "green", "blue"] checks whether the item "green" occurs anywhere in the list.

  2. 2
    List non-membership

    The expression "yellow" not in ["red", "green", "blue"] checks whether "yellow" does not occur in the list.

  3. 3
    String membership

    The expression "py" in "python" checks for the substring "py" anywhere within the larger string.

Result

Membership tests search the contents of lists and strings. For strings, the item being searched for can be a substring.

Finding One Item by Position

Indexing retrieves a single item from a sequence by using square brackets with an index. Positive indexing starts at 0 for the first item and increases toward the end. Negative indexing counts backward: -1 identifies the last item, -2 identifies the item before it, and so on.

0red-3red1green-2green2blue-1bluesame itemsame itemsame item
How do positive indices count from the beginning while negative indices count backward from the end?
Worked example

Reading from Both Ends

Use the sequence ["red", "green", "blue"] to identify the item selected by index 0 and the item selected by index -1.

  1. 1
    Positive index

    Index 0 starts at the beginning, so it selects "red".

  2. 2
    Negative index

    Index -1 starts counting from the end, so it selects "blue".

Result

Index 0 selects the first item, while index -1 selects the last item.

Key point

An index selects one item. That is the essential difference between indexing and slicing.

Extracting Portions with Slices

Slicing extracts a portion of a sequence with the form [start:stop:step]. Start identifies where selection begins and is included. Stop identifies where selection ends and is excluded. Step controls the interval between selected items. A step of 2 takes every second item, a step of 3 takes every third item, and a negative step reverses the direction.

0astartincluded1bstopexcluded2cstepinterval3d4ebegins atends beforeselects at interval
Which elements are included or skipped when different start, stop, and step values are applied to a sequence?
Worked example

Reading a Slice

Interpret the slice [1:5:2] for the sequence ["a", "b", "c", "d", "e", "f"].

  1. 1
    Start

    Selection begins at index 1, so the item at index 1 is included.

  2. 2
    Stop

    Selection stops before index 5, so the item at index 5 is excluded.

  3. 3
    Step

    A step of 2 selects every second item while moving forward.

Result

The selected items are the items at indices 1 and 3: "b" and "d".

Consistent Operations Across Types

Membership tests, indexing, and slicing work on lists, tuples, and strings. The behavior of the operation is consistent across these sequence types. Indexing a string treats each character as an item, and slicing a string extracts a substring. The result of a slice matches the input sequence type: a list produces a list, a tuple produces a tuple, and a string produces a string.

listmembershiptupleindexingstringslicingsupportssupportssupportssupportssupportssupportssupportssupportssupports
Which membership, indexing, and slicing operations work consistently across lists, tuples, and strings?
Sequence typeMembershipIndexingSlicing result
ListChecks for an itemRetrieves one itemA list
TupleChecks for an itemRetrieves one itemA tuple
StringChecks for a character or substringRetrieves one characterA string

The three operations follow consistent sequence behavior, while the result retains the input sequence type.

Mistakes to Catch Early

  • Common mistake

    Treating index 1 as the first item

    What it looks like

    Using index 1 when you intend to retrieve the beginning of a sequence

    Why it fails

    Positive indexing starts at 0, so index 1 identifies the second item.

    Do this instead

    Use index 0 for the first item.

  • Common mistake

    Including the stop position in a slice

    What it looks like

    Interpreting [1:4] as including the item at index 4

    Why it fails

    The stop position is excluded.

    Do this instead

    Select positions beginning at start and stop before stop.

  • Common mistake

    Forgetting that negative indices count from the end

    What it looks like

    Reading -1 as the first item

    Why it fails

    Negative indexing begins at -1 for the last item and counts backward.

    Do this instead

    Use -1 for the last item, -2 for the item before it, and so on.

  • Common mistake

    Expecting string membership to check only one character

    What it looks like

    Using a multi-character item with in on a string

    Why it fails

    String membership can search for a substring anywhere in the larger string.

    Do this instead

    Interpret the searched item as a character or substring when the sequence is a string.

  • Common mistake

    Confusing an index with a slice

    What it looks like

    Expecting a single index to return a portion of a sequence

    Why it fails

    Indexing retrieves one item, while slicing extracts a portion.

    Do this instead

    Use an index for one position and [start:stop:step] for a range.

Practice the Selection Rules

MEDIUM

For the sequence ["north", "east", "south", "west"], identify the item selected by index 0, the item selected by index -1, and the items selected by the slice [1:4:2]. Then decide whether "south" in the sequence is true. Finally, for the string "sequence", identify what kind of result indexing produces and what kind of result slicing produces.

Hints
  • Positive index 0 refers to the beginning.
  • Negative index -1 refers to the end.
  • For [1:4:2], start at index 1, stop before index 4, and move by 2.
  • Membership on a string can search for a substring.

What do you think happens?

For the sequence ["north", "east", "south", "west"], what does the slice [1:4:2] select?

  • ["east", "south"]

  • ["east", "west"]

  • ["north", "south"]

Reveal answer
Answer:

["east", "west"]

The slice starts at index 1, excludes index 4, and advances by 2. It therefore selects indices 1 and 3.

Key Takeaways

  1. 1
    Use in and not in to test whether an item exists anywhere in a sequence.
  2. 2
    Use square brackets with one index to retrieve a single item; positive indices begin at 0 and negative indices begin at -1 from the end.
  3. 3
    Use [start:stop:step] to extract a portion; start is included, stop is excluded, and step controls the interval or direction.
  4. 4
    Membership tests, indexing, and slicing work consistently on lists, tuples, and strings.
  5. 5
    Indexing a string retrieves one character, while slicing a string retrieves a substring.

At a glance

  • Membership tests answer whether an item occurs in a sequence.
  • Indexing selects one item using positive or negative positions.
  • Slicing selects a portion using an inclusive start, an exclusive stop, and an optional step.
  • The same three operations apply to lists, tuples, and strings, with results that match the input sequence type.
  • Strings treat characters as indexed items and support substring membership and slicing.

Related concepts

More concepts starting with M