All Python Methods – List, Tuple, Set and Dictionary with Examples

All Python Methods – List, Tuple, Set and Dictionary

 with Examples

Published on Code with Py  |  Category: Python Basics  |  Reading time: ~18 min

You have already learned about Python ListsTuplesSets, and Dictionaries separately. This post is your complete reference guide — all methods of all four data structures in one place, with clear examples and outputs for every single method. Bookmark this page and use it whenever you need a quick reference while coding.

Table of Contents

  1. Quick Cheat Sheet – All Methods at a Glance
  2. All List Methods with Examples
  3. All Tuple Methods with Examples
  4. All Set Methods with Examples
  5. All Dictionary Methods with Examples
  6. Comparison – Which Method Belongs Where
  7. FAQ

1. Quick Cheat Sheet – All Methods at a Glance

List Methods (11)

  • append(x)
  • insert(i, x)
  • extend(iter)
  • remove(x)
  • pop(i)
  • clear()
  • sort()
  • reverse()
  • index(x)
  • count(x)
  • copy()

Tuple Methods (2)

  • count(x)
  • index(x)

Set Methods (15)

  • add(x)
  • update(iter)
  • remove(x)
  • discard(x)
  • pop()
  • clear()
  • copy()
  • union()
  • intersection()
  • difference()
  • symmetric_difference()
  • issubset()
  • issuperset()
  • intersection_update()
  • difference_update()

Dictionary Methods (10)

  • keys()
  • values()
  • items()
  • get(k, d)
  • update(d)
  • pop(k)
  • popitem()
  • clear()
  • copy()
  • setdefault(k, v)

2. All List Methods with Examples

Python List – 11 Methods

list is ordered, mutable, and allows duplicates. It has the most methods out of all four data structures.

MethodWhat it doesSyntax
append(x)Adds item x to the endlist.append(x)
insert(i, x)Inserts x at index ilist.insert(1, x)
extend(iter)Adds all items from another iterablelist.extend([4,5])
remove(x)Removes first occurrence of xlist.remove(x)
pop(i)Removes and returns item at index ilist.pop(0)
clear()Removes all itemslist.clear()
sort()Sorts list in ascending orderlist.sort()
reverse()Reverses the list in placelist.reverse()
index(x)Returns index of first occurrence of xlist.index(x)
count(x)Counts how many times x appearslist.count(x)
copy()Returns a shallow copy of the listlist.copy()

append() – Add item to end

fruits = ["Apple", "Banana"]
fruits.append("Mango")
print(fruits)
['Apple', 'Banana', 'Mango']

insert() – Add item at specific position

fruits = ["Apple", "Mango"]
fruits.insert(1, "Banana")   # Insert at index 1
print(fruits)
['Apple', 'Banana', 'Mango']

extend() – Merge two lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
[1, 2, 3, 4, 5, 6]
extend() adds each item individually. append() adds the entire object as one item. So list.append([4,5]) gives [1,2,3,[4,5]] while list.extend([4,5]) gives [1,2,3,4,5].

remove() – Delete by value

nums = [10, 20, 30, 20]
nums.remove(20)   # Removes FIRST occurrence only
print(nums)
[10, 30, 20]

pop() – Delete by index and return value

nums = [10, 20, 30, 40]
removed = nums.pop(1)   # Remove index 1
print(f"Removed: {removed}")
print(nums)
nums.pop()              # No index = removes last item
print(nums)
Removed: 20
[10, 30, 40]
[10, 30]

sort() – Sort in ascending or descending order

marks = [85, 42, 90, 67, 55]
marks.sort()
print("Ascending: ", marks)
marks.sort(reverse=True)
print("Descending:", marks)
Ascending:  [42, 55, 67, 85, 90]
Descending: [90, 85, 67, 55, 42]

reverse() – Flip the list order

nums = [1, 2, 3, 4, 5]
nums.reverse()
print(nums)
[5, 4, 3, 2, 1]

index() and count()

nums = [10, 20, 30, 20, 20]
print(nums.index(30))    # Position of 30
print(nums.count(20))    # How many times 20 appears
2
3

clear() and copy()

original = [1, 2, 3]
backup = original.copy()   # Independent copy
original.clear()
print("Original:", original)
print("Backup:  ", backup)
Original: []
Backup:   [1, 2, 3]
Never do backup = original if you want an independent copy. That just creates a second reference to the same list — changes to one affect the other. Always use copy().

3. All Tuple Methods with Examples

Python Tuple – 2 Methods

tuple is immutable — once created it cannot be changed. That is why it has only 2 built-in methods. Both are read-only operations.

MethodWhat it doesSyntax
count(x)Returns number of times x appears in the tuplet.count(x)
index(x)Returns index of first occurrence of xt.index(x)

count() – Count occurrences

marks = (85, 90, 85, 78, 85, 92)
print(marks.count(85))   # How many times 85 appears
print(marks.count(99))   # 99 not in tuple
3
0

index() – Find position of a value

fruits = ("Apple", "Banana", "Mango", "Banana")
print(fruits.index("Mango"))    # Position of Mango
print(fruits.index("Banana"))   # FIRST occurrence of Banana
2
1
Even though tuples only have 2 methods, you can still use powerful built-in functions with them: len()max()min()sum()sorted(), and in operator all work perfectly with tuples.

Built-in functions that work with tuples

scores = (88, 92, 75, 60, 95)

print("Length: ", len(scores))
print("Maximum:", max(scores))
print("Minimum:", min(scores))
print("Sum:    ", sum(scores))
print("Sorted: ", sorted(scores))   # Returns a list
print("90 in? ", 90 in scores)
Length:  5
Maximum: 95
Minimum: 60
Sum:     410
Sorted:  [60, 75, 88, 92, 95]
90 in?   False

4. All Set Methods with Examples

Python Set – 15 Methods

set is unordered, mutable, and stores only unique values. It has the richest set of mathematical operations.

MethodWhat it does
add(x)Adds a single item to the set
update(iter)Adds multiple items from any iterable
remove(x)Removes x — raises KeyError if not found
discard(x)Removes x — no error if not found
pop()Removes and returns a random item
clear()Removes all items
copy()Returns a copy of the set
union(s2)Returns all items from both sets (A | B)
intersection(s2)Returns common items only (A & B)
difference(s2)Items in this set but not in s2 (A - B)
symmetric_difference(s2)Items not common to both sets (A ^ B)
issubset(s2)True if all items of this set are in s2
issuperset(s2)True if this set contains all items of s2
intersection_update(s2)Keeps only common items (modifies in place)
difference_update(s2)Removes items that exist in s2 (modifies in place)

add() and update()

s = {1, 2, 3}
s.add(4)
print(s)
s.update([5, 6, 7])
print(s)
s.update({8, 9}, [10])   # Multiple iterables
print(s)
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

remove() vs discard()

s = {10, 20, 30}
s.remove(20)
print(s)
s.discard(99)    # 99 not in set – no error
print(s)
s.remove(99)     # This WILL raise KeyError
{10, 30}
{10, 30}
KeyError: 99

union(), intersection(), difference(), symmetric_difference()

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print("Union:           ", A.union(B))
print("Intersection:    ", A.intersection(B))
print("Difference A-B:  ", A.difference(B))
print("Difference B-A:  ", B.difference(A))
print("Symmetric Diff:  ", A.symmetric_difference(B))
Union:            {1, 2, 3, 4, 5, 6}
Intersection:     {3, 4}
Difference A-B:   {1, 2}
Difference B-A:   {5, 6}
Symmetric Diff:   {1, 2, 5, 6}

issubset() and issuperset()

A = {1, 2}
B = {1, 2, 3, 4}

print(A.issubset(B))    # Is A inside B? True
print(B.issuperset(A))  # Does B contain A? True
print(B.issubset(A))    # Is B inside A? False
True
True
False

intersection_update() and difference_update()

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

A.intersection_update(B)   # Keeps only common – modifies A
print("After intersection_update:", A)

C = {1, 2, 3, 4}
C.difference_update(B)     # Removes items in B from C
print("After difference_update:",   C)
After intersection_update: {3, 4}
After difference_update:   {1, 2}
intersection_update() and difference_update() modify the original set in place — no new set is created. Use regular intersection() and difference() when you want to keep the originals unchanged.

5. All Dictionary Methods with Examples

Python Dictionary – 10 Methods

dictionary stores key-value pairs. Its methods are focused on accessing, updating, and managing those pairs.

MethodWhat it does
keys()Returns a view of all keys
values()Returns a view of all values
items()Returns a view of all key-value pairs as tuples
get(key, default)Returns value for key — returns default if key not found
update(dict2)Adds or updates items from another dictionary
pop(key)Removes key and returns its value
popitem()Removes and returns the last inserted key-value pair
clear()Removes all items from the dictionary
copy()Returns a shallow copy of the dictionary
setdefault(key, val)Returns value if key exists, else inserts key with val

keys(), values(), items()

student = {"name": "Rohan", "age": 21, "marks": 85}

print(student.keys())
print(student.values())
print(student.items())

# Convert to list
print(list(student.keys()))
print(list(student.values()))
dict_keys(['name', 'age', 'marks'])
dict_values(['Rohan', 21, 85])
dict_items([('name', 'Rohan'), ('age', 21), ('marks', 85)])
['name', 'age', 'marks']
['Rohan', 21, 85]

get() – Safe value access

student = {"name": "Rohan", "age": 21}

print(student.get("name"))           # Rohan
print(student.get("city"))           # None – key not found
print(student.get("city", "Unknown")) # "Unknown" – custom default
Rohan
None
Unknown

update() – Add or change multiple keys

student = {"name": "Rohan", "age": 21}
student.update({"city": "Bengaluru", "age": 22})
print(student)
{'name': 'Rohan', 'age': 22, 'city': 'Bengaluru'}

pop() and popitem()

student = {"name": "Rohan", "age": 21, "city": "Bengaluru"}

val = student.pop("age")
print(f"Removed age: {val}")
print(student)

last = student.popitem()
print(f"Last pair removed: {last}")
print(student)
Removed age: 21
{'name': 'Rohan', 'city': 'Bengaluru'}
Last pair removed: ('city', 'Bengaluru')
{'name': 'Rohan'}

setdefault() – Add key only if it does not exist

student = {"name": "Rohan", "age": 21}

# Key exists – returns existing value, does NOT change it
print(student.setdefault("age", 99))

# Key does not exist – inserts it with given value
print(student.setdefault("city", "Bengaluru"))

print(student)
21
Bengaluru
{'name': 'Rohan', 'age': 21, 'city': 'Bengaluru'}

clear() and copy()

original = {"a": 1, "b": 2, "c": 3}
backup = original.copy()
original.clear()
print("Original:", original)
print("Backup:  ", backup)
Original: {}
Backup:   {'a': 1, 'b': 2, 'c': 3}

6. Comparison – Which Method Belongs Where

This quick reference table helps you remember which methods are available in which data structure.

MethodListTupleSetDict
append()
insert()
extend()
add()
update()
remove()
discard()
pop()✅ (by index)✅ (random)✅ (by key)
clear()
copy()
sort()
reverse()
index()
count()
union() / intersection()
keys() / values() / items()
get() / setdefault()

Quick Summary – What You Learned
  • List has 11 methods — the most out of all four, because it is fully mutable
  • Tuple has only 2 methods (count, index) — because it is immutable
  • Set has 15 methods — rich with mathematical operations like union and intersection
  • Dictionary has 10 methods — focused on key-value access and management
  • remove() exists in both list and set, but behaves differently — list removes by value, set raises KeyError if not found
  • pop() exists in list (by index), set (random), and dict (by key) — all different!
  • update() exists in set (adds items) and dict (adds/updates key-value pairs)
  • Always use copy() to make an independent copy — never use = for this
  • setdefault() is a powerful dict method — adds key only if it does not already exist

Frequently Asked Questions (FAQ)

Q1. Why does tuple have only 2 methods when list has 11?

Because tuples are immutable — they cannot be changed after creation. All 11 list methods that are missing from tuple (like append, remove, sort) involve modifying the sequence. Since tuples cannot be modified, those methods simply do not exist for them. Only count() and index() are allowed because they just read the data.

Q2. What is the difference between remove() in list and set?

Both remove a specified value. But in a list, if the value appears multiple times, only the first occurrence is removed. In a set, remove() raises a KeyError if the value is not found — use discard() instead for safe removal in sets.

Q3. What is the difference between pop() in list, set, and dictionary?

In a list, pop(i) removes and returns the item at index i (default is the last item). In a set, pop() removes and returns a random item — you cannot control which one. In a dictionary, pop(key) removes and returns the value for the specified key.

Q4. What is the difference between update() in set and dictionary?

In a set, update() adds all items from another iterable (list, set, etc.) to the set. In a dictionary, update() adds new key-value pairs from another dictionary, and also updates existing keys with new values if they already exist.

Q5. How is sort() different from sorted()?

list.sort() modifies the original list directly and returns None. sorted() is a built-in function that works on any iterable, returns a new sorted list, and leaves the original unchanged. sorted() also works on tuples and sets while sort() only works on lists.

Q6. Can I use list methods on a tuple or set?

No. Methods are specific to each data type. You cannot call list.append() on a tuple or set. However, you can convert between types using list(), tuple(), set() functions and then use the appropriate methods on the converted type.


Found this reference helpful? Bookmark this page and share it with your classmates. Drop your questions in the comments!

"Knowing all methods of a data structure is like knowing all the tools in your toolbox — you become unstoppable."

Comments

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Control Flow Statements – Complete Guide with Real-Life Examples

Python Loops Explained – for Loop and while Loop with Examples and Output