Python Tuple, Set, and Dictionary Methods with Examples
Tuple Methods
1. count(x): Returns the number of times x appears in the tuple.
Example:
t = (1, 2, 3, 2)
print(t.count(2)) # Output: 2
2. index(x): Returns the first index of value x.
Example:
t = (1, 2, 3)
print(t.index(2)) # Output: 1
Set Methods
1. add(x): Adds element x to the set.
s = {1, 2}
s.add(3)
print(s) # {1, 2, 3}
2. remove(x): Removes x; raises KeyError if not present.
s = {1, 2}
s.remove(2)
print(s) # {1}
3. discard(x): Removes x if present.
s = {1, 2}
s.discard(2)
print(s) # {1}
4. pop(): Removes and returns an arbitrary set element.
s = {1, 2}
s.pop() # Random element
5. clear(): Removes all elements.
s = {1, 2}
s.clear()
print(s) # set()
6. union(), intersection(), difference(), symmetric_difference()
s1 = {1, 2}
s2 = {2, 3}
print(s1.union(s2)) # {1, 2, 3}
Dictionary Methods
1. get(key): Returns value for key, or None if not found.
d = {'a': 1}
print(d.get('a')) # 1
Python Tuple, Set, and Dictionary Methods with Examples
2. keys(), values(), items()
d = {'a': 1}
print(d.keys()) # dict_keys(['a'])
print(d.values()) # dict_values([1])
print(d.items()) # dict_items([('a', 1)])
3. update(other_dict): Updates with key-value pairs from other_dict.
d = {'a': 1}
d.update({'b': 2})
print(d) # {'a': 1, 'b': 2}
4. pop(key): Removes key and returns its value.
d = {'a': 1}
d.pop('a') # 1
5. popitem(): Removes and returns last inserted item.
d = {'a': 1, 'b': 2}
print(d.popitem())
6. clear(): Removes all items.
d = {'a': 1}
d.clear()
print(d) # {}
7. setdefault(key, default): Returns value or sets it to default.
d = {'a': 1}
d.setdefault('b', 2)
print(d) # {'a': 1, 'b': 2}