Thursday, 10 July 2025

Insert an element into the array at user defined position.

Insert an element into the array at user defined position.

Learn how to insert an element at any position in an array

array_insertion.c
#include <stdio.h>

int main() {
    int arr[20], n, i, pos, value;

    // Input current size of array
    printf("Enter number of elements (max 19): ");
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Input value and position to insert
    printf("Enter the element to insert: ");
    scanf("%d", &value);
    printf("Enter the position (0 to %d): ", n);
    scanf("%d", &pos);

    // Shift elements to the right
    for(i = n; i > pos; i--) {
        arr[i] = arr[i - 1];
    }

    // Insert the new value
    arr[pos] = value;
    n++;  // increase size

    // Display updated array
    printf("\nArray after insertion:\n");
    for(i = 0; i < n; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides essential input/output functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Other standard I/O operations

๐Ÿ”น Step 2: Declare Variables and Array

int arr[20], n, i, pos, value;
  • arr[20]: Array with maximum capacity of 20 elements
  • n: Current number of elements in the array
  • pos: Position where new element will be inserted
  • value: The element to be inserted
  • i: Loop counter variable

๐Ÿ”น Step 3: Input Array Elements

printf("Enter number of elements (max 19): ");
scanf("%d", &n);

for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}
  • First gets the current size of the array (n)
  • Then collects each element from the user
  • Stores elements sequentially in the array
  • Limits to 19 elements to leave space for insertion

๐Ÿ”น Step 4: Input Position and Value to Insert

printf("Enter the element to insert: ");
scanf("%d", &value);
printf("Enter the position (0 to %d): ", n);
scanf("%d", &pos);
  • Gets the new value to be inserted
  • Gets the insertion position (0 to n)
  • Valid positions are between 0 and current size (n)

๐Ÿ”น Step 5: Shift Elements to the Right

for(i = n; i > pos; i--) {
    arr[i] = arr[i - 1];
}
  • Starts from the end of the array
  • Moves each element one position to the right
  • Creates space at the insertion point
  • Works backwards to avoid overwriting data

๐Ÿ”น Step 6: Insert the New Value

arr[pos] = value;
n++;
  • Places the new value at the specified position
  • Increments the array size counter (n)
  • Maintains array integrity

๐Ÿ”น Step 7: Display the Updated Array

for(i = 0; i < n; i++) {
    printf("arr[%d] = %d\n", i, arr[i]);
}
  • Prints all elements including the new insertion
  • Shows both index and value for each element
  • Verifies the successful insertion

๐Ÿงช Sample Output

Enter number of elements (max 19): 5
Enter 5 elements:
arr[0]: 10
arr[1]: 20
arr[2]: 30
arr[3]: 40
arr[4]: 50
Enter the element to insert: 99
Enter the position (0 to 5): 2

Array after insertion:
arr[0] = 10
arr[1] = 20
arr[2] = 99
arr[3] = 30
arr[4] = 40
arr[5] = 50

๐Ÿ“Œ Key Concepts Covered

Array Operations
Manipulating fixed-size collections of elements in memory
Element Insertion
Adding new elements at specific positions by shifting existing elements
Right Shifting
Moving array elements to higher indices to create space for insertion
Position Validation
Ensuring insertion position is within valid bounds (0 to current size)
Size Management
Tracking and updating the current number of elements in the array

Create an array of size 10, find the largest value from the array.

Create an array of size 10, find the largest value from the array.

Learn how to find the maximum value in an array using C programming

find_max.c
#include <stdio.h>

int main() {
    int arr[10], i, max;

    // Input elements in the array
    printf("Enter 10 elements:\n");
    for(i = 0; i < 10; i++) {
        printf("arr[%d]: ", i);
        scanf("%d", &arr[i]);
    }

    // Assume first element is the largest
    max = arr[0];

    // Compare with other elements
    for(i = 1; i < 10; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }

    // Display the largest value
    printf("\nThe largest value in the array is: %d\n", max);

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides essential input/output functions:

  • printf() for displaying output
  • scanf() for reading user input
  • Other standard I/O operations

๐Ÿ”น Step 2: Declare Array and Variables

int arr[10], i, max;
  • arr[10]: Array to store 10 integer values
  • i: Loop counter for array traversal
  • max: Variable to store the maximum value

๐Ÿ”น Step 3: Input Elements in the Array

for(i = 0; i < 10; i++) {
    printf("arr[%d]: ", i);
    scanf("%d", &arr[i]);
}
  • Prompts user to enter 10 values
  • Stores each value in the array
  • Uses %d format specifier for integers
  • Displays current index with arr[%d]

๐Ÿ”น Step 4: Assume First Element as Maximum

max = arr[0];
  • Initializes max with first array element
  • Provides a starting point for comparison
  • Common algorithm pattern for finding max/min

๐Ÿ”น Step 5: Compare and Find the Largest

for(i = 1; i < 10; i++) {
    if(arr[i] > max) {
        max = arr[i];
    }
}
  • Starts loop from index 1 (since index 0 is already in max)
  • Compares each element with current max
  • Updates max if larger value is found
  • Implements linear search algorithm

๐Ÿ”น Step 6: Display the Result

printf("\nThe largest value in the array is: %d\n", max);
  • Prints the final maximum value
  • Uses %d to format the integer output
  • Includes newline characters for clean formatting

๐Ÿงช Sample Output

Enter 10 elements:
arr[0]: 23
arr[1]: 45
arr[2]: 12
arr[3]: 99
arr[4]: 34
arr[5]: 67
arr[6]: 88
arr[7]: 54
arr[8]: 11
arr[9]: 76

The largest value in the array is: 99

๐Ÿ“Œ Key Concepts Covered

Array Declaration
Creating a fixed-size collection of elements with int arr[size]
Linear Search
Sequentially checking each element to find the maximum value
Conditional Logic
Using if statements to compare values
Loop Control
Using for loops to traverse arrays
Variable Initialization
Starting with a sensible default value (first element)

Create arrays A, B of size 3, C of size 6, merge A and B into C.

Create arrays A, B of size 3, C of size 6, merge A and B into C.

Learn how to merge two arrays into a third array in C

merge_arrays.c
#include <stdio.h>

int main() {
    int A[3], B[3], C[6];
    int i;

    // Input elements of array A
    printf("Enter 3 elements of array A:\n");
    for(i = 0; i < 3; i++) {
        printf("A[%d]: ", i);
        scanf("%d", &A[i]);
    }

    // Input elements of array B
    printf("\nEnter 3 elements of array B:\n");
    for(i = 0; i < 3; i++) {
        printf("B[%d]: ", i);
        scanf("%d", &B[i]);
    }

    // Merge A into C
    for(i = 0; i < 3; i++) {
        C[i] = A[i];
    }

    // Merge B into C
    for(i = 0; i < 3; i++) {
        C[i + 3] = B[i];
    }

    // Display merged array C
    printf("\nMerged array C:\n");
    for(i = 0; i < 6; i++) {
        printf("C[%d] = %d\n", i, C[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This header provides:

  • printf() for output display
  • scanf() for user input
  • Standard I/O functions

๐Ÿ”น Step 2: Declare Arrays and Variable

int A[3], B[3], C[6];
int i;
  • A[3] and B[3]: Input arrays (3 elements each)
  • C[6]: Output array for merged result
  • i: Loop counter for array operations

๐Ÿ”น Step 3: Input Elements in Array A

for(i = 0; i < 3; i++) {
    printf("A[%d]: ", i);
    scanf("%d", &A[i]);
}
  • Prompts user for 3 values
  • Stores them in array A
  • Uses %d format for integers

๐Ÿ”น Step 4: Input Elements in Array B

for(i = 0; i < 3; i++) {
    printf("B[%d]: ", i);
    scanf("%d", &B[i]);
}
  • Same process as Step 3
  • Stores values in array B
  • Maintains parallel indexing

๐Ÿ”น Step 5: Merge Array A into C

for(i = 0; i < 3; i++) {
    C[i] = A[i];
}
  • Copies A[0] to C[0]
  • Copies A[1] to C[1]
  • Copies A[2] to C[2]

๐Ÿ”น Step 6: Merge Array B into C

for(i = 0; i < 3; i++) {
    C[i + 3] = B[i];
}
  • Copies B[0] to C[3]
  • Copies B[1] to C[4]
  • Copies B[2] to C[5]
  • Uses index shifting (i + 3)

๐Ÿ”น Step 7: Display Merged Array C

for(i = 0; i < 6; i++) {
    printf("C[%d] = %d\n", i, C[i]);
}
  • Prints all 6 elements of C
  • Shows index and value for each
  • Uses \n for newlines

๐Ÿงช Sample Output

Enter 3 elements of array A:
A[0]: 10
A[1]: 20
A[2]: 30

Enter 3 elements of array B:
B[0]: 40
B[1]: 50
B[2]: 60

Merged array C:
C[0] = 10
C[1] = 20
C[2] = 30
C[3] = 40
C[4] = 50
C[5] = 60

๐Ÿ“Œ Key Concepts Covered

Array Declaration
Creating fixed-size collections of elements with int arr[size]
Array Merging
Combining two arrays by copying elements sequentially
Index Shifting
Using C[i + 3] to place elements after existing ones
for Loop
Iterating through arrays with precise index control
I/O Operations
Using printf() and scanf() for console interaction

Create arrays A, B and C of size 3, perform C = A + B.

Create arrays A, B and C of size 3, perform C = A + B.

Learn how to perform element-wise addition of two arrays in C

array_addition.c
#include <stdio.h>

int main() {
    int A[3], B[3], C[3];
    int i;

    // Input elements of array A
    printf("Enter 3 elements of array A:\n");
    for(i = 0; i < 3; i++) {
        printf("A[%d]: ", i);
        scanf("%d", &A[i]);
    }

    // Input elements of array B
    printf("\nEnter 3 elements of array B:\n");
    for(i = 0; i < 3; i++) {
        printf("B[%d]: ", i);
        scanf("%d", &B[i]);
    }

    // Add elements of A and B, store in C
    for(i = 0; i < 3; i++) {
        C[i] = A[i] + B[i];
    }

    // Display result
    printf("\nResultant array C (A + B):\n");
    for(i = 0; i < 3; i++) {
        printf("C[%d] = %d\n", i, C[i]);
    }

    return 0;
}

๐Ÿงพ Step-by-Step Explanation

๐Ÿ”น Step 1: Include Header File

#include <stdio.h>

This includes the standard input-output library which provides:

  • printf() for output display
  • scanf() for user input
  • Other essential I/O functions

๐Ÿ”น Step 2: Declare Arrays and Variables

int A[3], B[3], C[3];
int i;
  • A[3] and B[3]: Arrays to store user inputs (3 elements each)
  • C[3]: Array to store the sum of corresponding elements
  • i: Loop counter variable for array traversal

๐Ÿ”น Step 3: Input Values in Array A

for(i = 0; i < 3; i++) {
    printf("A[%d]: ", i);
    scanf("%d", &A[i]);
}

This loop:

  • Runs 3 times (i = 0 to 2)
  • Prompts user for each element with index position
  • Stores input values in array A
  • Uses &A[i] to get memory address for storage

๐Ÿ”น Step 4: Input Values in Array B

for(i = 0; i < 3; i++) {
    printf("B[%d]: ", i);
    scanf("%d", &B[i]);
}

Similar to Step 3, but for array B:

  • Same loop structure
  • Stores values in array B
  • Maintains parallel indexing with array A

๐Ÿ”น Step 5: Add Corresponding Elements

for(i = 0; i < 3; i++) {
    C[i] = A[i] + B[i];
}

Performs element-wise addition:

  • Adds A[0] + B[0] and stores in C[0]
  • Adds A[1] + B[1] and stores in C[1]
  • Adds A[2] + B[2] and stores in C[2]
  • Process is called vector addition

๐Ÿ”น Step 6: Display Result

for(i = 0; i < 3; i++) {
    printf("C[%d] = %d\n", i, C[i]);
}

Outputs the result array C:

  • Prints each element with its index
  • Uses \n for newline between elements
  • Shows the sum of corresponding elements from A and B

๐Ÿงช Sample Output

Enter 3 elements of array A:
A[0]: 2
A[1]: 4
A[2]: 6

Enter 3 elements of array B:
B[0]: 1
B[1]: 3
B[2]: 5

Resultant array C (A + B):
C[0] = 3
C[1] = 7
C[2] = 11

๐Ÿ“Œ Key Concepts Covered

Array
A linear data structure that stores elements of the same type in contiguous memory
Element-wise Addition
Adding corresponding elements from two arrays of the same size
for Loop
Control structure used to traverse and process array elements sequentially
Array Indexing
Accessing individual array elements using their position (0-based index)
I/O Operations
Using printf() and scanf() for formatted output and input

Create an array of size 10, input values and display sum and average of all elements in the array.

Create an array of size 10, input values and display sum and average of all elements in the array.

array_sum_avg.c
#include <stdio.h>

int main() {
    int arr[10], i, sum = 0;  // Step 1: Declare array and variables
    float avg;

    // Step 2: Input elements from user
    printf("Enter 10 integers:\n");
    for(i = 0; i < 10; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &arr[i]);
    }

    // Step 3: Calculate sum
    for(i = 0; i < 10; i++) {
        sum += arr[i];
    }

    // Step 4: Calculate average
    avg = sum / 10.0;

    // Step 5: Display results
    printf("\nSum of all elements = %d", sum);
    printf("\nAverage of all elements = %.2f", avg);

    return 0;
}

๐Ÿง  Step-by-Step Explanation

๐Ÿ”น Step 1: Variable Declaration

int arr[10], i, sum = 0;
float avg;
  • arr[10] creates an integer array with 10 elements
  • sum initialized to 0 to accumulate total
  • avg declared as float for precise division
  • i will be used as loop counter

๐Ÿ”น Step 2: Input Array Elements

for(i = 0; i < 10; i++) {
    scanf("%d", &arr[i]);
}
  • Loop runs 10 times (i = 0 to 9)
  • Prompts user for each element
  • Stores input in array using index i
  • &arr[i] gets memory address for storage

๐Ÿ”น Step 3: Calculate Sum

for(i = 0; i < 10; i++) {
    sum += arr[i];
}
  • Iterates through each array element
  • Adds each element's value to sum
  • After loop completes, sum contains total

๐Ÿ”น Step 4: Calculate Average

avg = sum / 10.0;
  • Divides sum by 10.0 (float division)
  • Using 10.0 instead of 10 ensures decimal result
  • Result stored in avg variable

๐Ÿ”น Step 5: Display Results

printf("\nSum of all elements = %d", sum);
printf("\nAverage of all elements = %.2f", avg);
  • First printf displays integer sum
  • Second printf shows average with 2 decimal places
  • %.2f format specifier controls decimal precision

๐Ÿ–จ️ Sample Output:

Enter 10 integers:
Element 1: 5
Element 2: 10
Element 3: 15
Element 4: 20
Element 5: 25
Element 6: 30
Element 7: 35
Element 8: 40
Element 9: 45
Element 10: 50

Sum of all elements = 275
Average of all elements = 27.50

๐Ÿ’ก Key Concepts:

  • Array Basics: Fixed-size collection of same-type elements
  • Loop Structures: for loops for controlled iteration
  • Type Conversion: Importance of 10.0 for float division
  • I/O Formatting: Using %.2f for decimal precision
  • Memory Management: Array elements stored contiguously

Tuesday, 8 July 2025

Strings and String Operations in Python

Strings and String Operations in Python

๐Ÿ”ถ What is a String?

A string is a sequence of characters enclosed in single quotes ('), double quotes ("), or even triple quotes (''' or """).

✅ Examples:

text1 = 'Hello'
text2 = "Python"
text3 = '''Data Science'''

A string can contain:

  • Letters: 'abc'
  • Numbers: '123' (as characters)
  • Symbols: '@#$'
  • Spaces: 'Data Science'

In Python, a string is immutable, meaning once it's created, it cannot be changed.

๐Ÿ”ถ How to Create a String

๐Ÿ”ธ Using quotes:

name = "Alice"
greeting = 'Hello!'

๐Ÿ”ธ Using str() constructor:

number = 123
string_number = str(number)   # '123'

๐Ÿ”ถ String Indexing and Slicing

✅ Indexing:

Each character in a string has a position called an index. Indexing starts from 0.

word = "Python"
print(word[0])   # 'P'
print(word[3])   # 'h'

You can also use negative indexing:

print(word[-1])  # 'n' (last character)
print(word[-2])  # 'o'

✅ Slicing:

Slicing means getting a part of the string.

word = "DataScience"
print(word[0:4])   # 'Data'
print(word[4:])    # 'Science'
print(word[:4])    # 'Data'
print(word[::2])   # 'Dt cec' (skips every second character)

๐Ÿ”ถ Basic String Operations

Operation Syntax / Example Description
Concatenation "Data" + "Science" Joins two strings → 'DataScience'
Repetition "Python" * 3 Repeats string → 'PythonPythonPython'
Length len("Python") Returns number of characters → 6
Membership 'D' in "Data" Checks if character exists → True
Looping for char in "AI": print(char) Iterates over characters

๐Ÿ”ถ String Methods (Built-in Functions)

Python provides many helpful functions (methods) to work with strings.

๐ŸŸฉ Common String Methods

Method Description Example
.lower() Converts to lowercase 'PYTHON'.lower() → 'python'
.upper() Converts to uppercase 'data'.upper() → 'DATA'
.title() Capitalizes each word 'machine learning'.title()
.strip() Removes spaces from both ends ' data '.strip() → 'data'
.replace(old, new) Replaces a part of the string 'AI'.replace('A','I')
.split(separator) Splits string into list 'a,b,c'.split(',') → ['a','b','c']
.join(list) Joins list into string ','.join(['a','b','c']) → 'a,b,c'
.find(substring) Finds first index of substring 'python'.find('t') → 2
.count(substring) Counts how many times a substring appears 'banana'.count('a') → 3
.startswith(sub) Checks if string starts with sub 'hello'.startswith('he') → True
.endswith(sub) Checks if string ends with sub 'file.txt'.endswith('.txt') → True

๐Ÿ”ถ Escape Characters

Escape characters are used to include special characters in strings.

Escape Code Description Example Output
\n New line Line 1
Line 2
\t Tab (space) Adds tab space
\' Single quote It's Python
\" Double quote He said "Hi"
\\ Backslash \
print("Hello\nWorld")      # prints on two lines
print("She said, \"Yes\"") # uses double quotes inside string

๐Ÿ”ถ String Formatting

Used to insert variables into strings.

✅ 1. Using f-strings (Modern & Preferred)

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

✅ 2. Using format()

print("My name is {} and I am {} years old.".format(name, age))

๐ŸŸฆ Real-life Applications in Data Science

Task How Strings Help
Reading file content File data is read as strings
Preprocessing text (NLP) Clean and format input strings
Parsing CSV/JSON/XML data Split and analyze text-based files
Converting input values Convert raw strings to usable formats
Displaying messages or dashboards Present data using formatted strings

๐Ÿง  Key Points to Remember

  • Strings are sequences of characters and are immutable.
  • You can use indexing and slicing to access parts of a string.
  • There are many built-in string methods to manipulate text.
  • Strings can be formatted using f-strings or .format().
  • Strings play a key role in file handling, web scraping, NLP, and more.

๐Ÿ“ Practice Questions

  1. Take a sentence from user input and count how many words it has.
  2. Write a program to reverse a string using slicing.
  3. Ask the user to enter a name, and check if it starts with a capital letter.
  4. Replace all spaces in a sentence with underscores (_).
  5. Check if a string is a palindrome (same forward and backward).

input() Function and Type Conversion in Python

input() Function and Type Conversion in Python

๐Ÿ”ถ 1. input() Function – Taking Input from the User

In many real-world programs, you don't just hard-code data — you take it from users. This is where the input() function comes in.

✅ What is input()?

It is a built-in function used to take input from the user.

Whatever the user types is always treated as a string (text) — even if it's a number.

๐Ÿ”ธ Syntax:

variable = input("Message to user: ")

๐Ÿ”ธ Example:

name = input("Enter your name: ")
print("Hello", name)

๐Ÿ”น Output:

Enter your name: Milan
Hello Milan

๐Ÿ”ถ 2. Behavior of input() – Always Returns a String

Let's try this:

age = input("Enter your age: ")
print(age)
print(type(age))

Even if you type 25, Python will treat it as '25' — a string, not a number.

๐Ÿ”ถ 3. Type Conversion – Changing the Type of a Value

Since input() gives us a string, we must convert it to other data types if needed (like int or float).

This is called type conversion or type casting.

✅ Common Type Conversion Functions

Function Converts to Example Output Type
int() Integer (whole number) int("5") <class 'int'>
float() Floating point (decimal) float("3.14") <class 'float'>
str() String (text) str(100) <class 'str'>
bool() Boolean (True/False) bool(1) <class 'bool'>
list() List list("abc") ['a', 'b', 'c']

๐Ÿ”ถ 4. Examples of Type Conversion with input()

๐Ÿ”ธ Example 1: Add two numbers entered by the user

a = input("Enter first number: ")
b = input("Enter second number: ")

# Without conversion
print("Sum:", a + b)  # Output: '105' if input is 10 and 5 (string concatenation)

# With conversion
a = int(a)
b = int(b)
print("Correct Sum:", a + b)  # Output: 15

๐Ÿ”ธ Example 2: Convert input to float

height = float(input("Enter your height in meters: "))
print("Your height is:", height, "meters")

๐Ÿ”ธ Example 3: Boolean conversion

response = input("Do you like Python? (yes/no): ")

if response.lower() == "yes":
    print(True)
else:
    print(False)

๐Ÿ”ถ 5. Chaining Input and Conversion Together

Instead of writing in two steps:

x = input("Enter a number: ")
x = int(x)

You can do it in one line:

x = int(input("Enter a number: "))

✅ This is cleaner and more efficient.

๐Ÿ”ถ 6. type() Function – Check Data Type

Use the type() function to check what type of data you are working with.

๐Ÿ”ธ Example:

x = input("Enter something: ")
print(type(x))  # Always <class 'str'>

y = int(input("Enter a number: "))
print(type(y))  # <class 'int'>

๐ŸŸฆ Real-life Use Cases in Data Science

Scenario Use of Input Type Conversion Required
User enters age input() Convert to int()
User enters product price input() Convert to float()
Ask user for yes/no feedback input() Compare as str.lower()
Enter list of items separated by commas input().split(",") Convert to list()

๐Ÿง  Key Points to Remember

  • input() always returns a string.
  • Use int(), float(), or bool() to convert data to other types.
  • Always validate or check input if necessary.
  • Use type() function to check the data type.
  • You can combine input() and type conversion in a single line.

๐Ÿ“ Practice Questions

  1. Take two numbers as input and print their multiplication.
  2. Ask user to enter their full name and print its length.
  3. Write a program to convert temperature from Celsius to Fahrenheit using:
    F = C × 9/5 + 32
  4. Ask user for age and check if the person is eligible to vote (age ≥ 18).

Comparison Table: List vs Tuple vs Set

Comparison Table: List vs Tuple vs Set

Feature List Tuple Set
Definition Ordered, mutable collection Ordered, immutable collection Unordered, mutable collection
Syntax [1, 2, 3] (1, 2, 3) {1, 2, 3} or set()
Order maintained? ✅ Yes ✅ Yes ❌ No
Indexing supported? ✅ Yes (e.g., list[0]) ✅ Yes (e.g., tuple[0]) ❌ No
Mutable (changeable)? ✅ Yes ❌ No ✅ Yes (but only items, not by index)
Allow duplicate values? ✅ Yes ✅ Yes ❌ No
Allow different data types? ✅ Yes ✅ Yes ✅ Yes
Used for General-purpose collection Fixed data that shouldn't change Mathematical operations, unique items
Methods available Many (append, pop, sort, etc.) Few (count, index) Set operations (union, intersection)
Performance Slower for membership tests Fast for fixed-size data Fastest for membership testing
Hashable? ❌ No ✅ Yes (if all items are hashable) ❌ No
Common use case Storing items in order Storing constant data Removing duplicates, fast lookup

๐Ÿ”ธ Example

# List
my_list = [1, 2, 3, 4, 4]

# Tuple
my_tuple = (1, 2, 3, 4)

# Set
my_set = {1, 2, 3, 4, 4}  # Output: {1, 2, 3, 4}

Key Takeaways

  • Lists are your go-to for ordered, mutable collections that need frequent modifications
  • Tuples are perfect for fixed data that shouldn't change (like coordinates or database records)
  • Sets excel at membership testing, removing duplicates, and mathematical operations
  • Choose the right data structure based on your needs for mutability, ordering, and uniqueness

Python Sets

Python Sets

✅ What is a Set in Python?

A set is a built-in data type in Python used to store multiple items in a single variable.

A set is:

  • Unordered: Items do not have a specific position or index.
  • Unchangeable: You cannot change items once they're added, but you can add or remove items.
  • Unindexed: You cannot access items using indexes.
  • No duplicates allowed: Every element in a set is unique.

Sets are mainly used when you want to:

  • Remove duplicate values
  • Perform mathematical operations like union, intersection, etc.

๐ŸŸจ How to Create a Set

You can create a set using curly braces {} or the set() constructor.

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

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

Note: An empty set must be created using set() and not {} (which creates a dictionary).

empty_set = set()   # Correct
wrong_set = {}      # This is a dictionary

๐ŸŸฉ Properties of Sets

Unordered

colors = {"red", "green", "blue"}
print(colors)  # Output order can be different every time

No Duplicates

items = {"pen", "pencil", "pen", "eraser"}
print(items)  # Output: {'pen', 'pencil', 'eraser'}

๐ŸŸง Accessing Set Items

You cannot access items by index. Instead, use a loop.

for item in fruits:
    print(item)

๐ŸŸฆ Adding Items to a Set

1. add() – Adds a single item

fruits.add("orange")

2. update() – Adds multiple items

fruits.update(["grape", "melon"])

๐ŸŸฅ Removing Items from a Set

1. remove() – Removes the item; gives error if not found

fruits.remove("banana")

2. discard() – Removes the item; does not give error if not found

fruits.discard("mango")

3. pop() – Removes a random item

item = fruits.pop()
print("Removed item:", item)

4. clear() – Empties the set

fruits.clear()

5. del – Deletes the entire set

del fruits

๐ŸŸซ Set Operations (Very Important for Data Science)

Let's take two sets:

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

1. Union – Combines both sets without duplicates

print(A | B)        # {1, 2, 3, 4, 5, 6}
print(A.union(B))

2. Intersection – Common elements

print(A & B)        # {3, 4}
print(A.intersection(B))

3. Difference – Items in A not in B

print(A - B)        # {1, 2}
print(A.difference(B))

4. Symmetric Difference – Items in A or B but not both

print(A ^ B)        # {1, 2, 5, 6}
print(A.symmetric_difference(B))

๐ŸŸช Set Methods (Summary Table)

Method Description
add(item) Adds a single item
update(iterable) Adds multiple items
remove(item) Removes item (error if not found)
discard(item) Removes item (no error if not found)
pop() Removes random item
clear() Empties the set
union(set) Returns all unique items from both sets
intersection(set) Returns common items
difference(set) Items in current set but not in another
symmetric_difference(set) Items not common in both sets

๐Ÿ”ท Use Cases of Sets in Data Science

Remove Duplicates in Data

data = [1, 2, 2, 3, 3, 3, 4]
unique_data = set(data)
print(unique_data)  # {1, 2, 3, 4}

Find Common Features/Items

features_A = {"height", "weight", "age"}
features_B = {"age", "blood_pressure"}
common = features_A & features_B  # {'age'}

Fast Lookup

Set operations like membership tests are faster than lists.

print("apple" in fruits)  # Very fast

๐Ÿง  Key Points to Remember

  • Sets do not allow duplicate values.
  • Sets are unordered — you can't rely on the position of elements.
  • Use sets for efficient membership testing and mathematical set operations.
  • Sets are mutable — you can add or remove items, but the items themselves must be immutable (e.g., no list inside a set).

๐Ÿ“ Practice Questions

  1. Create a set of even numbers between 1 and 10.
  2. Given two sets A and B, find:
    • Elements common to both
    • Elements only in A
    • Elements in either A or B but not both
  3. Write a function that removes duplicate words from a sentence using sets.

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...