Thursday, May 26, 2022

Sequence methods

The following methods are common to most sequence types, such as lists, tuples, sets, and strings, except where indicated:

  • x in seq: True if an item within the sequence is equal to x; otherwise, False is returned. This also applies to a subset of a sequence, such as looking for a specific character within a string.
  • x not in seq: True if no item within the sequence is equal to x; otherwise, False is returned.
  • seq1 + seq2: Concatenates two sequences; if immutable sequences, a new object is created.
  • seq * n: Adds a sequence to itself n times.
  • seq[i]: Returns the i'th item of a sequence, with the first object's index value = 0.
  • seq[i:j]: Returns a slice of the sequence, from i (inclusive) to j (exclusive). Not available with sets.
  • seq[i:j:k]: Returns a slice of the sequence, from i (inclusive) to j (exclusive), skipping every k values. Not available with sets.
  • len(seq): Returns the length of a sequence; that is, the number of items within the sequence.
  • min(seq): Returns the smallest item in a sequence.
  • max(seq): Returns the largest item in a sequence.
  • seq.index(x[, i[, j]]): Returns the index value for the first occurrence of value x in a sequence; optionally, the first occurrence at or after index value i but before index j. Not available with sets.
  • seq.count(x): Returns the total number of occurrences of x in a sequence. Not available with sets.

The following methods are common to all mutable sequence types, such as lists and strings, except where indicated:

  • seq[i] = x: Item i within a sequence is replaced with x.
  • seq[i:j] = iter: A slice of seq, from i (inclusive) to j (exclusive), is replaced with the contents of iterable object iter. Not available with sets.
  • del seq[i:j]: Deletes the given slice in seq. Not available with sets.
  • seq[i:j:k] = iter: A slice of the sequence, from i (inclusive) to j (exclusive), skipping every k values, is replaced by the contents of iter. Not available with sets.
  • del seq[i:j:k]: Deletes a slice of seq, skipping every k value. Not available with sets.
  • seq.append(x): Appends x to the end of seq. Not available with sets; use set.add(x) instead.
  • seq.clear(): Deletes all contents of seq.
  • seq.copy(): Makes a new copy of seq.
  • seq.extend(iter): Extends the sequence with the contents of iter.
  • Not available with sets; use set.union(*others) instead.
  • seq *= n: Updates the sequence with n copies of itself. Not available with sets.
  • seq.insert(i, x): Inserts item x into the sequence at index value i.
  • seq.pop([i]): Returns the item at index i and removes it from the sequence.
  • s.remove(x): Deletes the first item from seq that equals x.
  • s.reverse(): Reverses the sequence in-place.

Next we'll cover the string methods.

Share:

0 comments:

Post a Comment