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