Fundamentals 16 min read

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.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master Python’s Core Data Structure Methods: Strings, Lists, Dictionaries, and Sets

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.

>> title = 'Python is the best language in the world'
>>> title.find('python')
-1
>>> title.find('the', 10)
10
>>> title.find('the', 11)
31

2. join(iterable) concatenates the elements of an iterable using the string as a separator; all elements must be strings.

>> '-'.join({'name':'chenyy','age':18})
'name-age'

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.

>> s = 'to be or not to be'
>>> s.split(' ')
['to', 'be', 'or', 'not', 'to', 'be']

4. lower() returns a copy of the string converted to lowercase.

>> 'Hello World'.lower()
'hello world'

5. title() capitalizes the first character of each word.

>> 'hello world'.title()
'Hello World'

6. replace(old, new) returns a new string where all occurrences of old are replaced by new .

>> 'this is test'.replace('test','demo')
'this is demo'

7. strip([chars]) removes the specified characters from both ends of the string.

>> '-*- coding:utf-8 -*-'.strip('-*-')
' coding:utf-8 '

8. swapcase() swaps the case of each character in the string.

>> "I love Python".swapcase()
'i LOVE pYTHON'

9. isalnum() checks whether the string consists only of alphanumeric characters.

>> 'python 666'.isalnum()
False
>>> 'python'.isalnum()
True
>>> '666'.isalnum()
True

10. isalpha() checks whether the string consists only of alphabetic characters.

>> 'python123'.isalpha()
False
>>> 'python'.isalpha()
True

11. isdigit() checks whether the string consists only of digits.

>> '123'.isdigit()
True
>>> 'python123'.isdigit()
False

12. startswith(str, start, end) returns True if the string begins with the specified prefix.

>> 'to be or not to be'.startswith('to')
True

13. endswith(str, start, end) returns True if the string ends with the specified suffix.

>> 'to be or not to be'.endswith('be')
True

List Methods

1. append(value) adds an element to the end of the list (in‑place).

>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

2. count(value) returns the number of occurrences of value in the list (also works for tuples and strings).

>> x = [[1, 2], 1, 1, [1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1

3. extend(iterable) appends each element from the iterable to the list (modifies the original list).

>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]

Equivalent effect can be achieved with slice assignment:

>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a[len(a):] = b
>>> a
[1, 2, 3, 4, 5, 6]

4. index(value) returns the index of the first occurrence of value ; raises ValueError if not found.

>> lst = [1, 2, 3]
>>> lst.index(2)
1

5. insert(index, value) inserts value at the given position; if the index is out of range, the value is appended.

>> lst = [1, 3, 4]
>>> lst.insert(1, 'two')
>>> lst
[1, 'two', 3, 4]

6. pop([index]) removes and returns the element at index (default last); the only list method that both mutates and returns a value.

>> lst = [1, 2, 3, 4, 5]
>>> lst.pop()
5
>>> lst.pop(1)
2

7. remove(value) deletes the first matching element; does not return a value.

>> lst = ['to', 'be', 'or', 'not', 'to', 'be']
>>> lst.remove('to')
>>> lst
['be', 'or', 'not', 'to', 'be']

8. reverse() reverses the list in place.

>> lst = [1, 2, 3, 4]
>>> lst.reverse()
>>> lst
[4, 3, 2, 1]

9. sort() sorts the list in place; all elements must be of comparable types.

>> lst = ['one', 'two', 'three', 'four']
>>> id(lst)
1652726159944
>>> lst.sort()
>>> lst
['four', 'one', 'three', 'two']
>>> id(lst)
1652726159944

Dictionary Methods

1. clear() removes all items from the dictionary (in‑place).

>> d = {'name':'chenyy','age':18}
>>> id(d)
1652725275168
>>> d.clear()
>>> d
{}
>>> id(d)
1652725275168

2. copy() returns a shallow copy of the dictionary.

>> d = {'name':'chenyy','age':18}
>>> d1 = d.copy()
>>> id(d)
1652726134608
>>> id(d1)
1652725275168
>>> d1
{'name':'chenyy','age':18}

3. fromkeys(iterable, default=None) creates a new dictionary with keys from the iterable and all values set to default (default is None).

>> dict().fromkeys(['name','age'])
{'name': None, 'age': None}
>>> dict.fromkeys(['name','age'],'null')
{'name': 'null', 'age': 'null'}

4. get(key, default=None) returns the value for key if present; otherwise returns default (default None).

>> d = {'name':'chenyy','age':18}
>>> d.get('sex')
>>> d.get('sex','boy')
'boy'

5. items() returns a view of the dictionary’s key‑value pairs.

>> d.items()
dict_items([('name', 'chenyy'), ('age', 18)])

6. keys() returns a view of the dictionary’s keys.

>> d.keys()
dict_keys(['name', 'age'])

7. values() returns a view of the dictionary’s values.

>> d.values()
dict_values(['chenyy', 18])

8. pop(key) removes the specified key and returns its value.

>> d = {'name':'chenyy','age':18}
>>> d.pop('age')
18
>>> d
{'name': 'chenyy'}

9. popitem() removes and returns an arbitrary (key, value) pair as a tuple.

>> d = {'name':'chenyy','age':18,'sex':'boy'}
>>> d.popitem()
('sex', 'boy')

10. setdefault(key, default=None) returns the value of key if it exists; otherwise inserts key with default and returns default .

>> d = {}
>>> d.setdefault('name','chenyy')
'chenyy'
>>> d
{'name': 'chenyy'}

11. update(iterable) merges another mapping or iterable of key‑value pairs into the dictionary; existing keys are overwritten.

>> d = {'sex':'boy'}
>>> id(d)
1782678051288
>>> d.update([('name','chenyy'),('age',18)])
>>> d
{'sex': 'boy', 'name': 'chenyy', 'age': 18}
>>> id(d)
1782678051288

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.

>> set1 = {1,2,3,4,5,6}
>>> set2 = {4,5,6,7,8,9}
>>> set1 - set2
{1, 2, 3}

2. intersection ( & ) returns common elements of both sets.

>> set1 & set2
{4, 5, 6}

3. union ( | ) returns all unique elements from both sets.

>> set1 | set2
{1, 2, 3, 4, 5, 6, 7, 8, 9}

4. symmetric_difference ( ^ ) returns elements that are in either set but not in both.

>> s1 = {1,2,3}
>>> s2 = {2,3,4}
>>> s1 ^ s2
{1, 4}

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 .

>> s2 <= s1
True

10. issuperset(other) ( >= ) checks whether the set contains all elements of other .

>> s1.issuperset(s2)
True

11. update(other) ( |= ) adds all elements from other to the set (in‑place).

>> set1 |= set2
>>> set1
{1, 2, 3, 4, 5, 6}

12. intersection_update(other) ( &= ) retains only elements found in both sets (in‑place).

>> set1 &= set2
>>> set1
{4, 5, 6}

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).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonString Methodsdictionary methodslist-methodsSet methods
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.