Thursday, 10 July 2025

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.

Sunday, 29 June 2025

Create an array of size 10, input values and print the array, and search an element in the array

Create an array of size 10, input values and print the array, and search an element in the array

array_operations.c
#include <stdio.h>

int main() {
    int arr[10];         // Step 1: Declare an array of size 10
    int i, search, found = 0;

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

    // Step 3: Print the array
    printf("\nThe array is:\n");
    for(i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }

    // Step 4: Search for an element
    printf("\n\nEnter the number to search: ");
    scanf("%d", &search);

    for(i = 0; i < 10; i++) {
        if(arr[i] == search) {
            printf("%d found at position %d (index %d)\n", search, i + 1, i);
            found = 1;
            break;
        }
    }

    if(!found) {
        printf("%d not found in the array.\n", search);
    }

    return 0;
}

๐Ÿง  Step-by-Step Explanation

๐Ÿ”น Step 1: Declare an array

int arr[10];
  • This line creates an integer array of size 10
  • It can store 10 elements of type int
  • Array indices range from 0 to 9

๐Ÿ”น Step 2: Take input from the user

for(i = 0; i < 10; i++) {
    scanf("%d", &arr[i]);
}
  • This loop runs from 0 to 9 (10 iterations)
  • We use scanf() to take user input
  • Each input is stored in consecutive array indices
  • &arr[i] gets the memory address of each element

๐Ÿ”น Step 3: Display the array

for(i = 0; i < 10; i++) {
    printf("%d ", arr[i]);
}
  • Prints each element of the array
  • Elements are separated by spaces
  • Output appears on a single line

๐Ÿ”น Step 4: Search for an element

scanf("%d", &search);
for(i = 0; i < 10; i++) {
    if(arr[i] == search) {
        // Print the found message
        break;
    }
}
  • First reads the number to search for
  • Linear search through the array elements
  • Compares each element with search value
  • If found, prints position and breaks the loop
  • If not found, displays appropriate message

๐Ÿ–จ️ Sample Output:

Enter 10 integers:
Element 1: 12
Element 2: 34
Element 3: 56
Element 4: 78
Element 5: 90
Element 6: 11
Element 7: 23
Element 8: 45
Element 9: 66
Element 10: 67

The array is:
12 34 56 78 90 11 23 45 66 67

Enter the number to search: 90
90 found at position 5 (index 4)

๐Ÿ’ก Key Concepts:

  • Array Declaration: Specifies size and type at compile time
  • Zero-based Indexing: First element is at index 0
  • Linear Search: Simple search algorithm checking each element sequentially
  • Loop Control: for loops provide precise iteration control
  • I/O Operations: printf and scanf for console input/output

Python Dictionaries

Python Dictionaries

๐Ÿ“˜ What is a Dictionary?

A dictionary in Python is a collection of key-value pairs. It's like a real-life dictionary where you look up a word (the key) to find its meaning (the value).

  • ๐Ÿ”‘ Keys → The unique identifiers
  • ๐Ÿ“ฆ Values → The data associated with those keys

๐Ÿ” Syntax:

my_dict = {
    "name": "Ansh",
    "age": 7,
    "grade": "1st"
}

Here:

  • "name", "age", and "grade" are the keys
  • "Ansh", 7, and "1st" are the values

๐Ÿงฉ Why Use a Dictionary?

  • To store related information (like name, marks, etc.) together
  • To quickly look up data using keys
  • It's organized and flexible

✍️ Creating a Dictionary

Example:

student = {
    "name": "Aarav",
    "age": 14,
    "class": "8th",
    "marks": 87
}

This creates a student dictionary with four key-value pairs.

๐ŸŽฏ Accessing Values

Use the key inside square brackets or the .get() method.

print(student["name"])   # Output: Aarav
print(student.get("marks"))  # Output: 87

➕ Adding New Items

student["school"] = "Tapasvi School"
print(student)

๐Ÿ” Updating a Value

student["marks"] = 92

❌ Removing Items

del student["class"]  # Removes the "class" key-value pair

Or:

student.pop("age")

๐Ÿ“š Useful Dictionary Methods

Method Description
dict.keys() Returns a list of all keys
dict.values() Returns a list of all values
dict.items() Returns key-value pairs as tuples
dict.update() Adds or updates items from another dict
dict.clear() Empties the dictionary

Example:

print(student.keys())    # dict_keys(['name', 'marks', 'school'])
print(student.values())  # dict_values(['Aarav', 92, 'Tapasvi School'])

๐Ÿ”„ Looping Through a Dictionary

Loop through keys:

for key in student:
    print(key)

Loop through keys and values:

for key, value in student.items():
    print(key, ":", value)

๐Ÿง  Nested Dictionaries

A dictionary can contain another dictionary. This is useful when storing complex data.

Example:

class_data = {
    "student1": {"name": "Riya", "marks": 90},
    "student2": {"name": "Aman", "marks": 85}
}

To access Riya's marks:

print(class_data["student1"]["marks"])  # Output: 90

✅ When to Use a Dictionary

Use a dictionary when:

  • You want to store pairs (like ID–name, product–price, etc.)
  • You need quick access to a value using a key
  • Order doesn't matter (though in Python 3.7+, order is preserved)

๐Ÿ”š Summary

  • A dictionary holds key-value pairs.
  • Keys must be unique and immutable (strings, numbers, etc.)
  • Values can be anything (numbers, strings, lists, even other dictionaries)
  • Great for organized and structured data

Friday, 27 June 2025

Lists in Python

Lists in Python

✅ What is a List?

A list is a collection of items in Python. You can think of it like a basket that holds multiple values—like numbers, words, or both.

A list:

  • Is ordered (items have a specific position)
  • Is changeable (you can add, remove, or update items)
  • Allows duplicate values

๐ŸŸข How to Create a List

Use square brackets [ ] to create a list:

students = ["ansh", "aarav", "mishti"]
numbers = [1, 2, 3, 4]
mixed = [1, "hello", 3.5, True]

You can also create an empty list:

empty_list = []

๐Ÿ”ข Accessing Items in a List

You can use indexing to access items in a list. Python indexes start from 0.

students = ["ansh", "aarav", "mishti"]
print(students[0])  # ansh
print(students[1])  # aarav

You can also use negative indexing:

print(students[-1])  # mishti (last item)

✏️ Changing List Items

Lists are mutable, meaning you can change values.

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)  # ['apple', 'mango', 'cherry']

➕ Adding Items to a List

append() – adds at the end:

fruits.append("orange")

insert() – adds at a specific position:

fruits.insert(1, "grape")  # inserts at index 1

❌ Removing Items from a List

remove() – removes by value:

fruits.remove("banana")

pop() – removes by index (default is last item):

fruits.pop()     # removes last
fruits.pop(0)    # removes first

clear() – removes all items:

fruits.clear()

๐Ÿ” Looping Through a List

You can use a for loop:

for fruit in fruits:
    print(fruit)

๐Ÿ“ Getting Length of a List

Use the len() function:

fruits = ["apple", "banana", "cherry"]
print(len(fruits))  # 3

๐Ÿ”„ Joining Two Lists

Use the + operator to combine two lists:

list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2  # [1, 2, 3, 4]

๐Ÿ” Checking for an Item

Use the in keyword:

if "apple" in fruits:
    print("Yes, apple is in the list")

๐Ÿงฉ List with Different Data Types

A list can have different types of data:

my_list = [10, "hello", True, 3.5]

๐Ÿงฑ Nested Lists

A list can contain another list (called a nested list):

nested = [1, 2, [3, 4]]
print(nested[2])      # [3, 4]
print(nested[2][1])   # 4

๐Ÿงช List Methods (Commonly Used)

Method Description
append() Adds item at the end
insert() Adds item at specific index
remove() Removes item by value
pop() Removes item by index
clear() Removes all items
sort() Sorts the list (ascending by default)
reverse() Reverses the list
index() Returns index of first match
count() Returns number of times item appears

๐Ÿ”ƒ Sorting a List

numbers = [3, 1, 4, 2]
numbers.sort()        # [1, 2, 3, 4]
numbers.sort(reverse=True)  # [4, 3, 2, 1]

๐Ÿ” Copying a List

list1 = [1, 2, 3]
list2 = list1.copy()

๐Ÿงฐ Converting List to Other Types

List to Tuple:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

✅ Summary

  • Lists are used to store multiple items in a single variable
  • Lists are ordered and changeable
  • You can add, remove, and update items
  • Lists support looping, sorting, nesting, and more
  • Lists are one of the most commonly used data structures in Python

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() ...