Master Python’s Core Data Structure Methods: Strings, Lists, Dictionaries, and Sets
This guide walks through Python’s essential string, list, dictionary, and set methods, explaining their behavior and showing interactive examples for searching, joining, splitting, case conversion, element manipulation, and set operations in detail.
String Methods
Note: strings are immutable and cannot be assigned via slicing.
1. find(str, start) returns the lowest index of the substring or -1 if not found; case‑sensitive.
<code>>> title = 'Python is the best language in the world'
>>> title.find('python')
-1
>>> title.find('the', 10)
10
>>> title.find('the', 11)
31</code>2. join(iterable) concatenates the elements of an iterable using the string as a separator; all elements must be strings.
<code>>> '-'.join({'name':'chenyy','age':18})
'name-age'</code>3. split(str, num) splits a string by the given separator into a list; num limits the number of splits. If no separator is provided, any whitespace is used.
<code>>> s = 'to be or not to be'
>>> s.split(' ')
['to', 'be', 'or', 'not', 'to', 'be']</code>4. lower() returns a copy of the string converted to lowercase.
<code>>> 'Hello World'.lower()
'hello world'</code>5. title() capitalizes the first character of each word.
<code>>> 'hello world'.title()
'Hello World'</code>6. replace(old, new) returns a new string where all occurrences of old are replaced by new .
<code>>> 'this is test'.replace('test','demo')
'this is demo'</code>7. strip([chars]) removes the specified characters from both ends of the string.
<code>>> '-*- coding:utf-8 -*-'.strip('-*-')
' coding:utf-8 '</code>8. swapcase() swaps the case of each character in the string.
<code>>> "I love Python".swapcase()
'i LOVE pYTHON'</code>9. isalnum() checks whether the string consists only of alphanumeric characters.
<code>>> 'python 666'.isalnum()
False
>>> 'python'.isalnum()
True
>>> '666'.isalnum()
True</code>10. isalpha() checks whether the string consists only of alphabetic characters.
<code>>> 'python123'.isalpha()
False
>>> 'python'.isalpha()
True</code>11. isdigit() checks whether the string consists only of digits.
<code>>> '123'.isdigit()
True
>>> 'python123'.isdigit()
False</code>12. startswith(str, start, end) returns True if the string begins with the specified prefix.
<code>>> 'to be or not to be'.startswith('to')
True</code>13. endswith(str, start, end) returns True if the string ends with the specified suffix.
<code>>> 'to be or not to be'.endswith('be')
True</code>List Methods
1. append(value) adds an element to the end of the list (in‑place).
<code>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]</code>2. count(value) returns the number of occurrences of value in the list (also works for tuples and strings).
<code>>> x = [[1, 2], 1, 1, [1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1</code>3. extend(iterable) appends each element from the iterable to the list (modifies the original list).
<code>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]</code>Equivalent effect can be achieved with slice assignment:
<code>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a[len(a):] = b
>>> a
[1, 2, 3, 4, 5, 6]</code>4. index(value) returns the index of the first occurrence of value ; raises ValueError if not found.
<code>>> lst = [1, 2, 3]
>>> lst.index(2)
1</code>5. insert(index, value) inserts value at the given position; if the index is out of range, the value is appended.
<code>>> lst = [1, 3, 4]
>>> lst.insert(1, 'two')
>>> lst
[1, 'two', 3, 4]</code>6. pop([index]) removes and returns the element at index (default last); the only list method that both mutates and returns a value.
<code>>> lst = [1, 2, 3, 4, 5]
>>> lst.pop()
5
>>> lst.pop(1)
2</code>7. remove(value) deletes the first matching element; does not return a value.
<code>>> lst = ['to', 'be', 'or', 'not', 'to', 'be']
>>> lst.remove('to')
>>> lst
['be', 'or', 'not', 'to', 'be']</code>8. reverse() reverses the list in place.
<code>>> lst = [1, 2, 3, 4]
>>> lst.reverse()
>>> lst
[4, 3, 2, 1]</code>9. sort() sorts the list in place; all elements must be of comparable types.
<code>>> lst = ['one', 'two', 'three', 'four']
>>> id(lst)
1652726159944
>>> lst.sort()
>>> lst
['four', 'one', 'three', 'two']
>>> id(lst)
1652726159944</code>Dictionary Methods
1. clear() removes all items from the dictionary (in‑place).
<code>>> d = {'name':'chenyy','age':18}
>>> id(d)
1652725275168
>>> d.clear()
>>> d
{}
>>> id(d)
1652725275168</code>2. copy() returns a shallow copy of the dictionary.
<code>>> d = {'name':'chenyy','age':18}
>>> d1 = d.copy()
>>> id(d)
1652726134608
>>> id(d1)
1652725275168
>>> d1
{'name':'chenyy','age':18}</code>3. fromkeys(iterable, default=None) creates a new dictionary with keys from the iterable and all values set to default (default is None ).
<code>>> dict().fromkeys(['name','age'])
{'name': None, 'age': None}
>>> dict.fromkeys(['name','age'],'null')
{'name': 'null', 'age': 'null'}</code>4. get(key, default=None) returns the value for key if present; otherwise returns default (default None ).
<code>>> d = {'name':'chenyy','age':18}
>>> d.get('sex')
>>> d.get('sex','boy')
'boy'</code>5. items() returns a view of the dictionary’s key‑value pairs.
<code>>> d.items()
dict_items([('name', 'chenyy'), ('age', 18)])</code>6. keys() returns a view of the dictionary’s keys.
<code>>> d.keys()
dict_keys(['name', 'age'])</code>7. values() returns a view of the dictionary’s values.
<code>>> d.values()
dict_values(['chenyy', 18])</code>8. pop(key) removes the specified key and returns its value.
<code>>> d = {'name':'chenyy','age':18}
>>> d.pop('age')
18
>>> d
{'name': 'chenyy'}</code>9. popitem() removes and returns an arbitrary (key, value) pair as a tuple.
<code>>> d = {'name':'chenyy','age':18,'sex':'boy'}
>>> d.popitem()
('sex', 'boy')</code>10. setdefault(key, default=None) returns the value of key if it exists; otherwise inserts key with default and returns default .
<code>>> d = {}
>>> d.setdefault('name','chenyy')
'chenyy'
>>> d
{'name': 'chenyy'}</code>11. update(iterable) merges another mapping or iterable of key‑value pairs into the dictionary; existing keys are overwritten.
<code>>> d = {'sex':'boy'}
>>> id(d)
1782678051288
>>> d.update([('name','chenyy'),('age',18)])
>>> d
{'sex': 'boy', 'name': 'chenyy', 'age': 18}
>>> id(d)
1782678051288</code>Set Methods
Note: frozenset() creates an immutable set; sets cannot contain mutable objects such as lists or dictionaries.
Non‑operator forms ( set.union() , set.intersection() , etc.) accept any iterable, while operator forms ( | , & , etc.) require another set.
1. difference ( - ) returns elements present only in the first set.
<code>>> set1 = {1,2,3,4,5,6}
>>> set2 = {4,5,6,7,8,9}
>>> set1 - set2
{1, 2, 3}</code>2. intersection ( & ) returns common elements of both sets.
<code>>> set1 & set2
{4, 5, 6}</code>3. union ( | ) returns all unique elements from both sets.
<code>>> set1 | set2
{1, 2, 3, 4, 5, 6, 7, 8, 9}</code>4. symmetric_difference ( ^ ) returns elements that are in either set but not in both.
<code>>> s1 = {1,2,3}
>>> s2 = {2,3,4}
>>> s1 ^ s2
{1, 4}</code>5. pop() removes and returns an arbitrary element; raises KeyError if the set is empty.
6. add(value) adds an element to the set.
7. remove(value) removes the specified element; raises KeyError if not present.
8. discard(value) removes the element if it exists; does nothing otherwise.
9. issubset(other) ( <= ) checks whether all elements of the set are contained in other .
<code>>> s2 <= s1
True</code>10. issuperset(other) ( >= ) checks whether the set contains all elements of other .
<code>>> s1.issuperset(s2)
True</code>11. update(other) ( |= ) adds all elements from other to the set (in‑place).
<code>>> set1 |= set2
>>> set1
{1, 2, 3, 4, 5, 6}</code>12. intersection_update(other) ( &= ) retains only elements found in both sets (in‑place).
<code>>> set1 &= set2
>>> set1
{4, 5, 6}</code>13. difference_update(other) ( -= ) removes all elements of other from the set (in‑place).
14. symmetric_difference_update(other) ( ^= ) updates the set to the symmetric difference of itself and other (in‑place).
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.