This page is a working reference for the methods you'll call most often on Python's built-in types. For each method, the important question isn't only what it does but what it returns and whether it changes the original object. Getting that wrong is behind bugs like names = names.sort() leaving names set to None.
title = " River Atlas "
clean = title.strip() # strings: return a new string
shelf = ["poems"]
shelf.append("maps") # lists: change in place, return NoneThe rule of thumb is: strings and tuples never change, so their methods return new values; lists, dictionaries and sets change in place, and their mutating methods return None. The tables below are grouped by type, with examples from a community library sorting donated books. For deeper explanations of collection methods, see advanced collection methods.
Strings
Strings are immutable: every method returns a new string (or another value) and leaves the original untouched.
| Method | Returns | Example result |
|---|---|---|
s.strip() / lstrip() / rstrip() | text without outer whitespace | "River Atlas" |
s.lower() / upper() / title() | text in another case | "river atlas" |
s.casefold() | aggressive lower case for comparisons | "straße" → "strasse" |
s.split(sep) / rsplit() | list of parts | ["River", "Atlas"] |
sep.join(items) | one string | "River-Atlas" |
s.replace(old, new) | text with replacements | |
s.startswith(x) / endswith(x) | bool; x may be a tuple | |
s.find(x) / index(x) | position; -1 / ValueError if absent | |
s.count(x) | number of occurrences | |
s.isdigit() / isalpha() | bool | |
s.removeprefix(p) / removesuffix(p) | text without that prefix/suffix (3.9+) | |
s.zfill(n) / center(n) / ljust(n) | padded text |
casefold() is the right choice for case-insensitive comparison, since it handles letters that lower() doesn't. removeprefix("ISBN-") removes an exact prefix; strip("ISBN-") would instead remove any of those characters from both ends.
Lists
List methods mostly change the list and return None:
| Method | Changes list? | Returns |
|---|---|---|
append(x) | yes | None |
extend(iterable) | yes | None |
insert(i, x) | yes | None |
remove(x) | yes | None (ValueError if absent) |
pop(i=-1) | yes | the removed item |
sort(key=, reverse=) | yes | None |
reverse() / clear() | yes | None |
index(x) / count(x) | no | int |
copy() | no | a shallow copy |
shelf = ["poems", "atlas"]
shelf.append(["maps", "guides"]) # one item: ['poems', 'atlas', ['maps', 'guides']]
shelf = ["poems", "atlas"]
shelf.extend(["maps", "guides"]) # two items: ['poems', 'atlas', 'maps', 'guides']When you need a sorted copy rather than an in-place sort, use the built-in sorted(shelf).
Mappings
| Method | Changes dict? | Returns |
|---|---|---|
get(k, default=None) | no | value or default |
keys() / values() / items() | no | live views |
update(other) | yes | None |
setdefault(k, default) | only if k missing | the value |
pop(k, default) | yes | the removed value |
popitem() | yes | last inserted (key, value) |
copy() | no | a shallow copy |
dict.fromkeys(keys, value) | no (class method) | a new dict |
donations = {"atlas": 2, "poems": 1}
for title, count in donations.items():
print(title, count)
print(donations.get("maps", 0)) # 0, and "maps" is not addedViews returned by keys(), values() and items() reflect later changes to the dictionary. Adding or removing keys while looping over a view raises RuntimeError: dictionary changed size during iteration; loop over list(donations) when you need to delete as you go.
Tuples and sets
Tuples are immutable and have just two methods, both read-only: count(x) and index(x).
Sets hold unique, hashable items and offer membership and set-algebra methods:
| Method | Changes set? | Returns |
|---|---|---|
add(x) | yes | None |
update(iterable) | yes | None |
remove(x) / discard(x) | yes | None (remove raises KeyError if absent) |
pop() | yes | an arbitrary item |
union, intersection, difference, symmetric_difference | no | a new set |
issubset, issuperset, isdisjoint | no | bool |
genres = ("fiction", "maps", "fiction")
print(genres.count("fiction")) # 2
print(set(genres)) # {'fiction', 'maps'} (order may vary)Set members must be hashable, so lists and dictionaries can't be added. Converting a list to a set removes duplicates but loses order and the duplicate count; use collections.Counter if you need the counts.
Choosing between look-alike methods
Several pairs of methods do almost the same job, and the difference decides whether your code fails loudly, fails silently or works:
| Pair | Difference |
|---|---|
s.find(x) / s.index(x) | find returns -1 when missing; index raises ValueError |
s.split() / s.split(" ") | no argument splits on any whitespace run and drops empty strings; " " splits on every single space, keeping empty strings |
d[k] / d.get(k) | [] raises KeyError; get returns None or a default |
set.remove(x) / set.discard(x) | remove raises KeyError; discard ignores a missing item |
list.sort() / sorted(list) | in place returning None / new list |
list.append(x) / list.extend(xs) | one item / each item of an iterable |
print("a b".split()) # ['a', 'b']
print("a b".split(" ")) # ['a', '', 'b']Prefer the version that raises when absence indicates a bug, and the forgiving version when absence is a normal case you handle.
Independent practice and a worked check
Task: create a method lookup table recording receiver type, return value and mutation behaviour for ten methods. Store it as a list of tuples and print it as aligned columns.
methods = [
("str", "strip", "new str", False), ("str", "split", "list", False),
("str", "replace", "new str", False), ("list", "append", "None", True),
("list", "sort", "None", True), ("list", "pop", "item", True),
("dict", "get", "value", False), ("dict", "update", "None", True),
("set", "add", "None", True), ("set", "union", "new set", False),
]
for owner, name, returns, mutates in methods:
print(f"{owner:<5}{name:<9}{returns:<9}{'mutates' if mutates else 'returns new'}")
print(sum(m for *_, m in methods), "of", len(methods), "mutate")The last line reports 5 of 10 mutate. For the worked check, the method that changes a list in place is list.sort; sorted() returns a new list instead.
Reference and next practice
The documentation describes string methods, sequence types, set types and mapping types. Continue with exception types and built-in functions. Practise with the Python exercises and Python quiz.
String and Collection Methods Reference Summary
- Strings: String methods such as strip, split, replace and casefold return transformed text rather than mutating the original.
- Lists: append and extend add values differently, while sort changes order in place.
- Mappings: keys, values and items expose dictionary views and get reads with a fallback.
- Tuples and sets: Tuples provide count and index while sets provide membership operations and update methods.
String and Collection Methods Reference Examples
Each example shows the code, the output it produces and what each part does.
String and Collection Methods Reference in a small program
title = " River Atlas "
print(title.strip().casefold())
donations = {"atlas": 2, "poems": 1}
print(sorted(donations.items()))
print(("fiction", "maps", "fiction").count("fiction"))river atlas
[('atlas', 2), ('poems', 1)]
2Line-by-line explanation
- Line 2
strip()removes the outer spaces andcasefold()lower-cases for comparison; both return new strings. - Line 4
items()gives (title, count) pairs;sorted()orders them by title. - Line 5The tuple method
count()finds two "fiction" labels.
Return values and mutation side by side
title = " The River Atlas "
print(repr(title.strip()), repr(title)) # new string; original unchanged
shelf = ["poems", "atlas"]
result = shelf.sort()
print(result, shelf) # None, list sorted in place
counts = {"atlas": 2}
print(counts.setdefault("maps", 0), counts) # inserts maps
print(counts.pop("atlas"), counts) # removes and returns
tags = {"fiction"}
print(tags.add("maps"), sorted(tags)) # add returns None
print(sorted(tags.union({"poems"})), sorted(tags)) # union returns a new set'The River Atlas' ' The River Atlas '
None ['atlas', 'poems']
0 {'atlas': 2, 'maps': 0}
2 {'maps': 0}
None ['fiction', 'maps']
['fiction', 'maps', 'poems'] ['fiction', 'maps']Line-by-line explanation
- Line 2The original string still has its spaces.
- Lines 5 to 6
sort()returnsNone; the list itself is now sorted. - Line 13
union()builds a new set;tagskeeps its two items.
Common String and Collection Methods Reference Mistakes
Expecting a string method to change the string
title = " River Atlas "
title.strip()
print(f"[{title}]") # [ River Atlas ]title = " River Atlas "
title = title.strip()
print(f"[{title}]") # [River Atlas]Assigning the result of list.sort()
titles = ["poems", "atlas"]
titles = titles.sort()
print(titles) # Nonetitles = sorted(["poems", "atlas"])String and Collection Methods Reference in Real Projects
Using this reference
Developers rarely memorise every method; they remember the patterns and look up the details. Keep two questions in mind whenever you call a method: does it change the object, and what does it return? Your editor's autocomplete shows each method's signature, and help(str.split) in the shell gives the full documentation.
Data cleaning relies heavily on string methods (strip, casefold, split, replace), reporting on dictionary methods (items, get, setdefault), and deduplication on sets. The same names appear in pandas, where df["title"].str.strip() applies a string method to a whole column.
String and Collection Methods Reference FAQ
How can I see all methods of a Python object?
Call dir(obj) in the shell for every attribute name, and help(obj) or help(type(obj).method) for documentation. Names with double underscores are special methods; the rest are the ones you normally call.
What is the difference between lower() and casefold()?
lower() converts to lower case for display. casefold() is designed for case-insensitive comparison and handles more characters, for example turning the German "ß" into "ss". Use casefold() when comparing text typed by people.
Which methods return None in Python?
Methods that change a mutable object in place: list.append, extend, insert, remove, sort, reverse, clear; dict.update and clear; set.add, update, remove, discard and clear. Returning None signals that no new object was created.
What is the difference between remove() and discard() on a set?
Both remove an item. remove() raises KeyError if the item isn't present, while discard() does nothing. Use remove() when a missing item indicates a bug, and discard() when it doesn't matter.
How do I remove a prefix from a string?
Use s.removeprefix("ISBN-") on Python 3.9 or later. It removes the exact prefix once. On older versions, check s.startswith(prefix) and slice with s[len(prefix):]. Avoid lstrip("ISBN-"), which removes any of those characters, not the prefix as a unit.
String and Collection Methods Reference Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Which method changes a list in place?
Which review concern is valid for string and collection methods reference?
String and Collection Methods Reference Quiz
2 questions to check what you learned.
Which method changes a list in place?
- sorted
- list.sort
- Python ignores the distinction
Which statement correctly describes mappings?
- keys, values and items expose dictionary views and get reads with a fallback.
- Only the example output matters, not the rule
- Every operation has the same behavior