Wednesday, 23 July 2025

Python Tuple , Set and Dict

 Tuple Methods :


t = (1, 2, 3)


t.count(2)            # 1

t.index(3)            # 2


#Set methods :

s = {1, 2, 3}

s.add(4)              # {1, 2, 3, 4}
s.remove(2)           # Removes 2
s.discard(5)          # Safe remove
s.pop()               # Removes random item
s.clear()             # Empties the set
s.update([5, 6])      # Add multiple

# Set operations:

a = {1, 2, 3}
b = {3, 4, 5}

a | b                 # Union
a & b                 # Intersection
a - b                 # Difference
a ^ b                 # Symmetric difference

a.issubset(b)
a.issuperset(b)
a.isdisjoint(b)

#Dict :

d = {'a': 1, 'b': 2}

d['a']                # 1
d.get('c', 0)         # 0 (default)
d.keys()              # dict_keys(['a', 'b'])
d.values()            # dict_values([1, 2])
d.items()             # dict_items([('a', 1), ('b', 2)])

d.update({'c': 3})    # Adds/updates keys
d.pop('a')            # Removes and returns value
d.popitem()           # Removes last inserted pair
d.clear()             # {}

# Dict comprehension:
{x: x**2 for x in range(5)}  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


No comments:

Post a Comment

Python Tuple , Set and Dict

 Tuple Methods : t = (1, 2, 3) t.count(2)            # 1 t.index(3)            # 2 #Set methods : s = {1, 2, 3} s.add(4)              # {1, ...