Skip to main content

Command Palette

Search for a command to run...

Best advanced python course

Updated
6 min read
Best advanced python course
B

I am Barun Tiwary, learning to scale software to millions of users.

Chapter 1: String, List, Set, Tuple, and Dictionary Operations


Project Name: Contact Management System (Basic Version)

Description: Create a simple CLI-based contact management system.

Flow and Features:

  1. Use strings for storing names and contact details.

  2. Use lists to maintain a collection of contacts.

  3. Perform operations like adding, updating, deleting, and viewing contacts.

  4. Use sets to ensure no duplicate contact names.

  5. Use tuples to store immutable contact details (e.g., name, phone number).

  6. Use dictionaries to map contact names to details for efficient searching.


Prerequisites.

Introduction to Strings and In-Built Data Structures.

Strings in Python

Strings are sequences of characters enclosed in quotes. Python supports single, double, and triple quotes for strings.

Creating Strings:

# Single-quoted string
greeting = 'Hello'

# Double-quoted string
name = "World"

# Triple-quoted string (used for multi-line strings)
message = '''This is a
multi-line string.'''

Accessing Characters in a String:

Strings in Python are indexed, starting from 0 for the first character.

text = "Python"
print(text[0])  # Output: 'P'
print(text[0:3]   # Output: 'Pyt' ([startIndex: lastIndex] - select from the startIndex to lastIndex - 1)
print(text[-1]) # Output: 'n' (negative index for last character)
print(text[-2])# Output: 'o'

Common String Methods:

text = "python programming"
print(text.upper())       # Output: 'PYTHON PROGRAMMING' (Converts to uppercase)
print(text.lower())       # Output: 'python programming' (Converts to lowercase)
print(text.capitalize())  # Output: 'Python programming' (Capitalizes the first character)
print(text.replace("python", "Java"))  # Output: 'Java Programming' Replace substring

String Slicing:

You can extract a portion of a string using slicing.

text = "Python"
print(text[0:3])  # Output: 'Pyt' (characters from index 0 to 2)
print(text[:3])   # Output: 'Pyt' (same as above)
print(text[3:])   # Output: 'hon' (from index 3 to the end)

Lists in Python

A list is a collection of items (elements) that are ordered and changeable. Lists are created using square brackets [].

Creating Lists:

# Creating a list of integers
numbers = [1, 2, 3, 4]

# Creating a mixed list
mixed = [1, "hello", 3.5, True]

Accessing List Items:

Lists use zero-based indexing.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: 'apple'
print(fruits[-1]) # Output: 'cherry'

Modifying List Items:

Lists are mutable, so you can change their content.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)  # Output: ['apple', 'blueberry', 'cherry']

Common List Methods:

numbers = [1, 2, 3]
numbers.append(4)        # Adds an item to the end
numbers.insert(1, 1.5)   # Inserts 1.5 at index 1
numbers.remove(2)        # Removes the first occurrence of 2
numbers.sort()           # Sorts the list
print(numbers)           # Output: [1, 1.5, 3, 4]

List Slicing:

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])  # Output: [20, 30, 40] (items at index 1, 2, and 3)
print(numbers[:3])   # Output: [10, 20, 30]
print(numbers[3:])   # Output: [40, 50]

1.2.1 Set

Sets in Python

A set is a collection of unique, unordered elements. Sets are created using curly braces {} or the set() function.

Creating a Set:

# Using curly braces
fruits = {"apple", "banana", "cherry"}

# Using the set() function
numbers = set([1, 2, 3, 4])

# Empty set
empty_set = set()

Accessing Elements in a Set:

Since sets are unordered, you cannot access elements using an index. You can use a loop:

for fruit in fruits:
    print(fruit)

Adding, Deleting, and Updating Elements:

# Adding elements
fruits.add("orange")

# Removing elements
fruits.remove("banana")  # Raises an error if not found
fruits.discard("banana") # Does not raise an error

# Updating with multiple elements
fruits.update(["kiwi", "mango"])

Python Set Operations:

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

print(A.union(B))        # Output: {1, 2, 3, 4, 5}
print(A.intersection(B)) # Output: {3}
print(A.difference(B))   # Output: {1, 2}
print(A.symmetric_difference(B)) # Output: {1, 2, 4, 5}

1.3.1 Tuple

Tuples in Python

A tuple is an immutable, ordered collection of elements. Tuples are created using parentheses ().

Creating Tuples:

# Empty tuple
empty_tuple = ()

# Tuple with elements
numbers = (1, 2, 3)

# Mixed tuple
mixed = (1, "hello", 3.5)

Accessing Tuples:

You can use indexing and slicing with tuples just like lists.

tuple_data = ("a", "b", "c", "d")
print(tuple_data[1])    # Output: 'b'
print(tuple_data[1:3])  # Output: ('b', 'c')

Tuples are Immutable:

Tuples cannot be modified after creation.

numbers = (1, 2, 3)
# numbers[1] = 4  # This will raise a TypeError

Built-In Tuple Functions:

numbers = (10, 20, 30)
print(len(numbers))      # Output: 3
print(max(numbers))      # Output: 30
print(min(numbers))      # Output: 10

1.4.1 Dictionary

Dictionaries in Python

A dictionary is an unordered collection of key-value pairs. Keys must be unique, and values can be of any type.

Creating Dictionaries:

# Using curly braces
details = {"name": "Alice", "age": 25, "city": "New York"}

# Using the dict() function
details = dict(name="Bob", age=30, city="London")

Accessing Items in Dictionaries:

details = {"name": "Alice", "age": 25}
print(details["name"])  # Output: 'Alice'
print(details.get("age")) # Output: 25

Adding, Upda

ting, and Removing Items:

# Adding or updating
details["city"] = "Paris"

# Removing
removed = details.pop("age")  # Removes 'age' and returns its value
details.clear()  # Clears the entire dictionary

Properties of Dictionary Keys:

  • Keys must be unique.

  • Keys must be immutable (e.g., strings, numbers, tuples).

Built-In Dictionary Methods:

details = {"name": "Alice", "age": 25}
print(details.keys())    # Output: dict_keys(['name', 'age'])
print(details.values())  # Output: dict_values(['Alice', 25])
print(details.items())   # Output: dict_items([('name', 'Alice'), ('age', 25)]

Project

# Contact Management System (Basic Version)
# This program is a simple CLI-based contact management system that demonstrates
# the use of strings, lists, sets, tuples, and dictionaries in Python.

# Contact management system data structure
# Dictionary to map contact names (keys) to tuples containing contact details (values)
contacts = {}

# Set to ensure no duplicate contact names
contact_names = set()

def add_contact():
    """Adds a new contact to the system."""
    name = input("Enter contact name: ").strip()
    if name in contact_names:
        print(f"Contact with name '{name}' already exists.\\n")
        return

    phone = input("Enter phone number: ").strip()
    email = input("Enter email address: ").strip()

    # Use a tuple to store immutable contact details
    contact_details = (phone, email)

    # Add to dictionary and set
    contacts[name] = contact_details
    contact_names.add(name)
    print(f"Contact '{name}' added successfully.\\n")

def view_contacts():
    """Displays all contacts in the system."""
    if not contacts:
        print("No contacts available.\\n")
        return

    print("\\n--- Contact List ---")
    for name, details in contacts.items():
        phone, email = details
        print(f"Name: {name}, Phone: {phone}, Email: {email}")
    print()

def update_contact():
    """Updates an existing contact."""
    name = input("Enter the name of the contact to update: ").strip()
    if name not in contact_names:
        print(f"Contact '{name}' does not exist.\\n")
        return

    phone = input("Enter new phone number: ").strip()
    email = input("Enter new email address: ").strip()

    # Update contact details
    contacts[name] = (phone, email)
    print(f"Contact '{name}' updated successfully.\\n")

def delete_contact():
    """Deletes a contact from the system."""
    name = input("Enter the name of the contact to delete: ").strip()
    if name not in contact_names:
        print(f"Contact '{name}' does not exist.\\n")
        return

    # Remove from dictionary and set
    del contacts[name]
    contact_names.remove(name)
    print(f"Contact '{name}' deleted successfully.\\n")

def search_contact():
    """Searches for a contact by name."""
    name = input("Enter the name of the contact to search: ").strip()
    if name in contacts:
        phone, email = contacts[name]
        print(f"\\nContact found: Name: {name}, Phone: {phone}, Email: {email}\\n")
    else:
        print(f"Contact '{name}' not found.\\n")

def main_menu():
    """Displays the main menu and handles user input."""
    while True:
        print("\\n--- Contact Management System ---")
        print("1. Add Contact")
        print("2. View Contacts")
        print("3. Update Contact")
        print("4. Delete Contact")
        print("5. Search Contact")
        print("6. Exit")

        choice = input("Enter your choice (1-6): ").strip()

        if choice == '1':
            add_contact()
        elif choice == '2':
            view_contacts()
        elif choice == '3':
            update_contact()
        elif choice == '4':
            delete_contact()
        elif choice == '5':
            search_contact()
        elif choice == '6':
            print("Exiting Contact Management System. Goodbye!")
            break
        else:
            print("Invalid choice. Please try again.\\n")

# Run the main menu
if __name__ == "__main__":
    main_menu()

More from this blog