Monday, 30 March 2026

Print the Sum of Number in range in python

 #Print the Sum of Number in range
#0,1,2,3,4,5,6,7,8,9,10
#0+1+2+3+4+5+6+7+8+9+10=55
num=int(input("Enter a number: "))
print(sum(i for i in range(1,num+1)))#--->Logic

Sunday, 29 March 2026

For Loop In Python zero to Hero

 For Loop In Python zero to Hero


Loop Means = repeat code multiple times

for Loop:  Used when you know how many times to repeat code 

#Let’s say you have a list of numbers, and you want to print each number.

numbers = [1, 2, 3, 4, 5]

hear Code 
                for number in numbers:
                        print(number)
#numbers is the sequence, which in this case is a defined list of numbers
#number is the loop variable that takes each value from the list, one at a time.
#print(number) is a statement in the code block that gets executed for each item in the list


Ranges and for loops
The range() function in Python generates a sequence of numbers. It is commonly used in for loops to iterate over a sequence of numbers. The range() function can take one, two, or three arguments:
range(stop): generates numbers from 0 to stop – 1.
range(start, stop): generates numbers from start to stop – 1.
range(start, stop, step): generates numbers from start to stop – 1, incrementing by step.

I want 5 Mulipcation Table

Number =5 table upto_means number range loop will excute tell them example i am giveing 11 menas 
5
.
.
.
50  range ok but i want table change Print Function  
number=int(input("Enter a number: "))
up_to=int(input("Enter a number: "))
for i in range(1, up_to):
print(f"{number} x {i} = {number * i}")
Output:
Enter a number: 5
Enter a number: 11
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Statements: break and continue with for loops


The break statement allows you to exit the loop before it is completed. When the break statement is executed, the loop terminates immediately, and the program continues with the next statement following the loop.

The continue statement allows skipping the current iteration of a loop and proceeding to the next iteration. When the continue statement is encountered, the next iteration begins

items = ['apple', 'banana', 'cherry', 'date', 'elderberry']

search_item = 'cherr'

for item in items:

    if item == search_item:

        print(f'Found {search_item}!')

        break

# Optional else clause

else:

    print(f'{search_item} not found.')

=======================================================

items1 = ['apple', 'banana', 'cherry', 'lemon', 'elderberry']

for items in items1:

    if 'a' in items:

        continue

    print(items)

================================================

In Python, enumerate() is a built-in function that adds a counter to an iterated item and returns it as an enumerated object. This can be especially useful for looping over a list, or any other item where both the index and the value of each item are needed.

As a developer, you can use these functions to make your code more readable and concise by eliminating the need to manually manage counter-variables. They also help reduce the risk of errors that can occur when manually incrementing a counter.

Here’s a simple example to illustrate how enumerate() can be used in a for loop:

# List of fruits

fruits = ['apple', 'banana', 'cherry']

# Using enumerate to get index and value

for index, fruit in enumerate(fruits, start=0   ):

    print(f"{index}: {fruit}")

===============================================

Real time Usage:=

In the following loop example, you can use a loop to automate processing files. The following loop scans a directory, separates files from folders, and provides a list of all the files inside with their local path.

import os


directory = '/path/to/directory'


# Iterate over all files in the directory


for filename in os.listdir(directory):


    file_path = os.path.join(directory, filename)


    if os.path.isfile(file_path):


        print(f'File: {filename, file_path}')


/path/to/directory is a placeholder to be replaced with the local path for the directory to be processed.

os.listdir(directory) lists all the entries in the specified directory.

os.path.join(directory, filename) constructs the full path to the file.

os.path.isfile(file_path) checks if the path is a file (and not a directory).

Knowing the exact location of files helps create precise backups and restore them when needed.

Pattern Prints in For loop

:#Pyramid Pattern (Important 🔥)

n = 5
for i in range(1, n+1):
print(" " * (n-i) + "*" * (2*i-1))

Output:-

 *

   ***

  *****

 *******

*********



Pprint & Pformat in Python

 If you import the pprint module into your programs, you’ll have access to the pprint() and pformat() functions that will “pretty print” a dictionary’svalues. This is helpful when you want a cleaner display of the items in a dictionary than what print() provides.

import pprint

message = "It was a bright cold day in April, and the clocks were striking thirteen."
count = {}
for character in message:
count.setdefault(character,
0)
count[character] = count[character] +
1
pprint.pprint(count)

The pprint.pprint() function is especially helpful when the dictionary itself contains nested lists or dictionaries. If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat() instead. These two lines are equivalent to each other:

Friday, 20 March 2026

Deep in Python list

 

Most Important in Python(0-Z)

1.What is List. Explain in Detail

         The list class is a fundamental built-in data type in Python        

Ø  Ordered: They contain elements or items that are sequentially arranged according to their specific insertion order.

Ø  Zero-based: They allow you to access their elements by indices that start from zero.

Ø  Mutable: They support in-place mutations or changes to their contained elements.

Ø  Heterogeneous: They can store objects of different types.

Ø  Growable and dynamic: They can grow or shrink dynamically, which means that they support the addition, insertion, and removal of elements.

Ø  Nestable: They can contain other lists, so you can have lists of lists.

Ø  Iterable: They support iteration, so you can traverse them using a loop or comprehension while you perform operations on each of their elements.

Ø  Sliceable: They support slicing operations, meaning that you can extract a series of elements from them.

Ø  Combinable: They support concatenation operations, so you can combine two or more lists using the concatenation operators.

In Python, lists are ordered, which means that they keep their elements in the order of insertion

 

Ex: a = [1, 2, 3, 4]

         shopping = ["Milk", "Eggs", "Bread"]

         list_name = [item1, item2, item3]

List is Mutable (VERY IMPORTANT)

👉 You can modify list after creation

Ex:-

Indexing (in List Access Elements):-

You can access an individual object in a list by its position or index in the sequence. Indices start from zero:

Synatx :list_object[index]

           Ex:list[0] – acess First Element in List

 

Type in Command Each below:-

course=["P","Y","T","H","O","N"]
print(course)
#Access First element in List
print("Access First element in List",course[0])
#Access last element in List
print("Access last element in List",course[-1])
#Above statement i don't know string elements that y use this one
print("Access last element in List",course[5])
#Above statement i  know string elements that y use this one
print("Access last using len function element in List",course[len(course)-1])
#aceess First two elements from list
print("Access last element in List",course[0,1]) --error Beasuce Index not work

Slicling:-

Retrieving Multiple Items From a List: Slicing

Syntax:- list_object[start:stop:step]

The [start:stop:step] part of this construct is known as the slicing operator. Its syntax consists of a pair of square brackets and three optional indices, start, stop, and step. The second colon is optional. You typically use it only in those cases where you need a step value different from 1.

  • start specifies the index at which you want to start the slicing. The resulting slice includes the item at this index.
  • stop specifies the index at which you want the slicing to stop extracting items. The resulting slice doesn’t include the item at this index.
  • step provides an integer value representing how many items the slicing will skip on each step. The resulting slice won’t include the skipped items.

                                  Index                           Default Value

                                  start                                    0

                                  stop                         len(list_object)

                                  step                                       1

Example:

letters = ["A", "a", "B", "b", "C", "c", "D", "d"]

I want Upper case letter From List

Index start with hear à0

Stop hear d(Means 8)

Step 2 counter

upper_letters = letters[0::2] –smart way

letters = ["A", "a", "B", "b", "C", "c", "D", "d"]
uppercase=letters[0:8:2]  --Understanding Way this also give same result
print(uppercase)

 

Home work Lower Case you Can try :

 

Pro Level:-

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#0 to 5 from list
print(digits[0:4]) # Res [0, 1, 2, 3]
print(digits[:4])  # Res [0, 1, 2, 3]
print(digits[-4:]) #res [6, 7, 8, 9]
print(digits[0:len(digits):2]) #res [0, 2, 4, 6, 8]
course=["P","Y","T","H","O","N"]
print(course[::-1]) # res ['N', 'O', 'H', 'T', 'Y', 'P']--revse String

To change the value of a given element in a list, you can use the following syntax:

list_object[index] = new_value

 

In Python, you’ll have two kinds of mechanisms to create copies of an existing list. You can create either:

1.   shallow copy

2.   deep copy

Both types of copies have specific characteristics that will directly impact their behaviour. In the following sections, you’ll learn how to create shallow and deep copies of existing lists in Python. First, you’ll take a glance at aliases, a related concept that can cause some confusion and lead to issues and bugs.

Methods in list:

List Methods

Let's look at different list methods in Python:

  • append(): Adds an element to the end of the list.

Syntax: list_name.append(element)

  • copy(): Returns a shallow copy of the list.

         Syntax: list_name.copy()

  • clear(): Removes all elements from the list.

Syntax: list_name.clear()

  • count(): Returns the number of times a specified element appears in the list.

         Syntax: list_name.count(element)

  • extend(): Adds elements from another list to the end of the current list.

         Syntax: list_name.extend(iterable)

  • index(): Returns the index of the first occurrence of a specified element.

Syntax: list_name.index(element)

  • insert(): Inserts an element at a specified position.

         Syntax: list_name.insert(index, element)

  • pop(): Removes and returns the element at the specified position (or the last element if no index is specified).

Syntax: list_name.pop(index)

  • remove(): Removes the first occurrence of a specified element.

Syntax: list_name.remove(element)

  • reverse(): Reverses the order of the elements in the list.

         Syntax: list_name.reverse()

  • sort(): Sorts the list in ascending order (by default).

Syntax: list_name.sort(key=None, reverse=False)

 

 

Max , Min,and there or more find your self map filter alos those this  your home work

 

 

 

 

 

 

 

 

 

 

Tuesday, 17 March 2026

Python list Interview Q&A

 #----------------List Interview Question For Zero to Adv Level--------

# Reverse a list

number=[10,30,20,40,60,90,80,100]

# using sort and reverse keyword we can use

number.sort(reverse=True)

print(number) # result [100, 90, 80, 60, 40, 30, 20, 10]

number1=[10,30,20,40,60,90,80,100]

#without Sort and reverse key word

print(number1[::-1]) #result [100, 80, 90, 60, 40, 20, 30, 10]

#2. Find largest & smallest

number2=[10,30,20,40,60,90,80,100]

print(max(number2)) # Max Number is 100

print(min(number2)) # Min Number is 10

print(sum(number2)) # Sum of Number is 430

#3.Count occurrences

number2=[10,30,20,40,20,20,20,60,90,80,100]

print(number2.count(20)) # Result is 4

#4.Remove duplicates

print(list(set(number2))) #[100, 40, 10, 80, 20, 90, 60, 30]

#5 Second_largest number in list

L1=list(set(number2)) # Remove Duplicates

L1.sort() # sort the List

print(L1[-2]) # Find the Second_Highest Number

mylist = ['apple', 'banana', 'cherry']

mylist[1:2] = ['kiwi', 'mango']

print(mylist) 

print(mylist[2])



Python List Full Infromation with Interview questions

 #LIST --List one of the data type in python

#A List is a collection of items stored in a single variable.

#list can store multiple values with comma speciation

#list we can identify  begins with an opening square bracket and

#ends with a closing square bracket, []

#A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].

# list is Ordered,Mutable (changeable),Allow duplicates ,Can store different data types

#

animals=["cat","rat","Cow","Hen","horse","dog"]

print("Name of the animals Is",animals)

#in List data type we can store String values ,Int values ,flote values anything

animals_digits=["cat","0","rat","1","Cow","2","Hen","3","horse","4","dog","5"]

print("Name of the animals Is",animals_digits)

#Just as an index can get a single value from a list,

#List value Index --> it will Index first value from list

print(animals_digits[0])

print(animals_digits[1]) #it will Index 2 value from list

print(animals_digits[2]) #it will Index 3 value from list

print(animals_digits[-1]) #it will Negative Index Last value from list

print(animals_digits[-2])

#a slice can get several values from a list, in the form of a new list

print(animals_digits[0:4]) # Get 0,1,2,3 values from List # means 0-cat,1-0,2-rat,3-1

text = "HELLO"

print(text[1])     # E

print(text[1:2])   # E (but type is different!)

text = "PYTHON"

print(text[::2]) # Result is PTO Means Step = 2 (skip one)

Blak = "Mahen"

print(Blak[1:10])

#-------------------------------------------------

text = "HELLO"

print(text[1:2] == text[1]) # Result should be True

# Both are 'E', but types conceptually differ (still equal)

#---------------------------------------------------

nums = [10, 20, 30, 40]

print(nums[-3:-1])

#While Slicing start included, stop excluded

#Changing the Values in List

nums[0]=200 # Old Nums [10, 20, 30, 40]

print(nums) #Result should be [200, 20, 30, 40]

#List Concatenation(+) and List Replication(*)

value=[1, 2, 3] + ['A', 'B', 'C']

print(value) # Result is:-[1, 2, 3, 'A', 'B', 'C']

value=[1,2,3]*2

print(value) # Result  Is:[1, 2, 3, 1, 2, 3]

#Removing Values from Lists with del Statements

del value[1] # Result  Is:[1, 2, 3, 1, 2, 3]

print(value) #Result [1, 3, 1, 2, 3]

#Adding Values to Lists with the append() and insert() Methods

# sy : string.append(value)

s1=[1,2,3,'python','java']

s1.append('C++')

print(s1) #[1, 2, 3, 'python', 'java', 'C++']

#Insert Method SY: Insert(index,object)

str=[1,2,3,'python','java']

str.insert(2,'C') #[1, 2, 'C', 3, 'python', 'java']

print(str)

#Removing Values from Lists with remove()

str1=[1,2,3,'python','java']

str1.remove(2)

print(str1) # result [1, 3, 'python', 'java']

#Sorting the Values in a List with the sort() Method

str2=[0,5,13,9,6,20,15]

str2.sort() # result [0, 5, 6, 9, 13, 15, 20]

print(str2)

str2.sort(reverse=True) # result [20, 15, 13, 9, 6, 5, 0]

print(str2)

str3=[1, 3, 2, 4, 'Alice', 'Bob']

#str3.sort()

print(str3) #TypeError: '<' not supported between instances of 'str' and 'int'

#A list value is a mutable data type: It can have values added, removed, or changed.

#List Copy

l1=str1.copy() #str1 copy into l1

print(l1)

#========== real Time Interview question ===============

#Find the largest Number in given LIST

Numbers=[10,20,30,50,60] # Largest Number is 60

print(max(Numbers))  #->60

#Find the second-largest number in List

Numbers=[10,20,70,50,90,15,20,80,20,25,100]

Numbers.sort(reverse=False)

print(Numbers[-2])  # result 90

# Remove Duplicates in Given List

Number1=[10,20,70,50,90,15,20,80,20,25,100]

unique=list(set(Number1))

print(unique) #-->[100, 70, 10, 15, 80, 50, 20, 25, 90]

# List Unpacking

a, b, c = [10, 20, 30]

print(a, b, c) #

print(a+b)

print(a)

#Reveses list Using Reverse keyword without using reverse key word

nums = [1,2,3,4]

nums.sort(reverse=True)

print(nums)

print(nums[::1])#-Result [4, 3, 2, 1]



Even and Odd Value Find in python along examption handling

try:

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

    if number % 2 == 0:

        print("Even")

    else:

        print("Odd")

except ValueError:

    print("Invalid input! Please enter a valid number.") 

Print the Sum of Number in range in python

 #Print the Sum of Number in range #0,1,2,3,4,5,6,7,8,9,10 #0+1+2+3+4+5+6+7+8+9+10=55 num=int(input("Enter a number: ")) print(sum...