Visit Website

Sets, Booleans, Tuples & Dictionaries

Understanding Core Python Data Structures: Sets, Booleans, Tuples & Dictionaries

Python offers a wide variety of built-in data types to help developers build powerful applications efficiently. Among these, Sets, Booleans, Tuples, and Dictionaries are essential foundational structures. In this blog post, we'll explore each of them, how they're constructed, when to use them, and key methods to master.

Sets in Python

A Set is an unordered collection of unique elements. This means it automatically filters out duplicates and doesn’t retain any order.

Creating and Using Sets

x = set()
x.add("Hello")
x.add(1)
x.add(2)

Output:

{1, 2, 'Hello'}

Note: Adding a duplicate (like x.add(1)) won’t affect the set. It only keeps unique values.

Casting a List to a Set (to remove duplicates)

list1 = [1,1,2,2,3,4,5,6,1,7,8,7,6,5,4,3,4]
unique_items = set(list1)
print(unique_items)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}

Common Set Operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
  • Intersection: a.intersection(b){3, 4}

  • Difference: a.difference(b){1, 2}

  • Union: a.union(b){1, 2, 3, 4, 5, 6}

These operations make sets ideal for membership tests, filtering duplicates, and performing mathematical operations like unions and intersections.

Booleans in Python

Python’s Boolean type represents one of two values: True or False. These are essential for controlling logic in your programs.

Basic Usage

a = True
b = False

Boolean from Comparisons

print(1 > 2)  # Output: False
print(2 <= 3) # Output: True

The None Object

Python also includes a special None object that acts as a placeholder:

b = None
if not b:
    print("Hurray!")  # Executes since `None` is falsy

Use None when you need a variable but don’t have a value to assign yet.

Tuples in Python

A Tuple is like a list, but immutable—you can’t change its values after creation. Tuples are ideal for fixed collections of items.

Creating Tuples

t = (7, 8, 9)
my_tuple = ("mausam", "Hello", "K xa", "Thik xa hajur", "Nice")

Accessing Elements

print(t[0])         # Output: 7
print(my_tuple[1:4])# Output: ('Hello', 'K xa', 'Thik xa hajur')

Tuple Methods

  • t.count('item'): Count how many times an item appears.

  • t.index('item'): Get the index of the first occurrence of an item.

t = ('one', 2, 'one', 2)
print(t.count('one'))  # Output: 2
print(t.index(2))      # Output: 1

Immutability Example

t[0] = 'change'  # ❌ Error: Tuples don’t support item assignment

Use tuples when you need data integrity—for example, fixed configuration values.

Dictionaries in Python

A Dictionary is a collection of key-value pairs. Unlike sequences (lists, tuples), dictionaries are accessed by keys.

Creating a Dictionary

my_dict = {
    'key1': 'value1',
    'key2': 'value2',
    'name': 'mausam',
    'addr': 'KTM'
}

Accessing Values

print(my_dict['name'])        # Output: mausam
print(my_dict.get('phone'))   # Output: None (safe access)

Modifying and Adding Items

my_dict['key1'] = 100
my_dict['phone'] = '9840123456'

Nested Dictionaries

nested = {
    'key1': {
        'nestkey': {
            'subnestkey': 'value',
            'name': 'Broadway'
        },
        'age': 'Hundred'
    }
}

print(nested['key1']['nestkey']['name'])  # Output: Broadway

Useful Dictionary Methods

d = {'key1': 1, 'key2': 2, 'key3': 3}
d.keys()    # dict_keys(['key1', 'key2', 'key3'])
d.values()  # dict_values([1, 2, 3])
d.items()   # dict_items([('key1', 1), ('key2', 2), ('key3', 3)])

Dictionaries are powerful for storing and accessing data with identifiers (keys) instead of relying on positions like lists or tuples.

Wrapping Up

Here’s a quick summary:

Data Type Mutable Ordered Unique Elements Access Type Use Case
Set Element Unique collection, set operations
Boolean Conditional logic, control flow
Tuple Index Immutable data
Dictionary ❌(until 3.7+) Keys must be unique Key Key-value mapping, data storage

Each of these data types serves a specific purpose, and mastering them sets the stage for more complex Python programming ahead.

Post a Comment

Visit Website
Visit Website
Mausam Welcome to WhatsApp chat
Hello! How can we help you today?
Type here...