0% found this document useful (0 votes)
58 views27 pages

IX-PYTHON-HISTORY-ALL LESSONSWFJO

Python, created by Guido van Rossum in 1989, has evolved into one of the most popular programming languages due to its simplicity and versatility. It has undergone significant updates, including the introduction of Python 3.0, which streamlined the language but posed migration challenges. Today, Python is widely used in web development, machine learning, and data science, making it a valuable skill for aspiring developers.

Uploaded by

potlaneeraj68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views27 pages

IX-PYTHON-HISTORY-ALL LESSONSWFJO

Python, created by Guido van Rossum in 1989, has evolved into one of the most popular programming languages due to its simplicity and versatility. It has undergone significant updates, including the introduction of Python 3.0, which streamlined the language but posed migration challenges. Today, Python is widely used in web development, machine learning, and data science, making it a valuable skill for aspiring developers.

Uploaded by

potlaneeraj68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

IX-AI-TYTHON

Python is one of the most popular programming languages of our time.


It is widely used by programmers around the world. Big tech
companies, small businesses, start-ups, freelancers – they are all
eager to use the capabilities it offers. What is the history of Python?
Who is behind its success?
In 2021, Python turned 30 and had a lot to celebrate. It is now among
the most popular programming languages ACCORDING TO A STACK
OVERFLOW REPORT .

There are many arguments for using Python. Its clarity and simplicity
make it the perfect choice for beginners. So, if you are still wondering
how to start your programming journey, learn Python with A
COMPREHENSIVE BASIC TRAINING PATH ONLINE . You can even start from
scratch!
It is one thing to learn Python. It is also interesting to understand how
Python has become what it is today. It has quite an impressive history.

A Benevolent Dictator for Life


It was Christmas time 1989 in the Netherlands. Guido van Rossum was
sitting at home thinking about how to spend a week off while the office
where he was working was closed. He wanted something interesting to
work on to keep him occupied.
At that time, he was working at Centrum Wiskunde & Informatica (CWI)
on the Amoeba project. It was a microkernel-based distributed system
for which he was developing system utilities. While on this project, van
Rossum realized that coding in C took a lot of time. He thought: how
useful would it be to create a language to help him complete his work
faster?
He wanted to create a scripting language, more easily programmable
and readable than shell scripts. It was to be a descendant of the ABC
language that would appeal to Unix and C hackers. With some free
time on his hand at Christmas, van Rossum began to flesh out the idea
that popped into his head.
He immediately came up with the name "Python" for his new hobby
project. He was a fan of the British surreal comedy troupe Monty
Python, and as he admits, it was suitably irreverent for what was
essentially a "skunkworks project." The name was short, catchy, a little
edgy, and in keeping with the tradition of naming programming
languages after famous people.

Guido van Rossum wanted this new language to be clear and easy to
learn. It is based on a simplified use of the English language and open-
source code. The philosophy of Python is summarized in "THE ZEN
OF PYTHON," which states the 19 guiding principles for writing
computer programs that have influenced the design of the Python
language. To display it, run the following command in the Python
interpreter:
CODE:

>>> import this

In 1995, van Rossum became Python's Benevolent Dictator for Life


(BDFL), a title first bestowed upon him and given to a small number of
open-source software development leaders. He had joined the
Corporation for National Research Initiatives to advance the language,
and they were forming a semi-formal group to oversee its development.
The term appeared in a follow-up mail by Ken Manheimer after one of
the meetings.
After many years of holding this iconic title, with the story of Python
already written in hundreds of pages, van Rossum announced in 2018
that he would step down as a BDFL of Python.
The Evolution of Python
Working at CWI (Centrum Wiskunde & Informatica) at that time, van
Rossum discussed the future of Python with his manager. They
eventually agreed to publish it open-source. It may seem obvious
today, but the business model for developing programming languages
was still unclear in 1991.

02.1991 Python 0.9.0


February 1991 was a historic date. Guido van Rossum published the
source code of the Python interpreter to alt.source, a Usenet group for
open-source code. Thus began the dynamic story of Python, and open-
sourcing helped Python succeed.
The first version, Python 0.9.0, was inspired by the ABC language van
Rossum was implementing at CWI at that time. Its main goal was to
take the best from ABC and fix the rest. This first Python release had
the following important features:
 Classes with inheritance exception handling.
 Functions.
 Modules.
 Core data types like list, dict, and str.

01.1994 Python 1.0


Another milestone in the history of Python came with the release of its
second version in January 1994. A separate Usenet group was created
for this purpose.
Additional functionalities were implemented with this version:
 Functional programming tools (lambda, map, filter,
and reduce).
 Support for complex numbers.
 Functions with keyword arguments.
The popularity of Python started to grow at that time. The National
Institute of Standards and Technology in the U.S. became interested in
using this new language for their standards-related projects. They
invited van Rossum as an expert to boost their Python skills.
Thanks to the NIST support, van Rossum started participating in
conferences. He was invited to lead workshops and spread information
about Python. As a result, some key contributors became interested in
the project and had a significant impact on the evolution of the
language.
A short time after, van Rossum was offered a position at CNRI
(Corporation for National Research Initiatives). This allowed him to
create a team of Python enthusiasts and release its subsequent
versions. Also, an official website and a mailing list were created for
Python.

10.2000 Python 2.0


With this version, Python started to build toward its future form as a
reliable language with a comfortable development experience.
Important features introduced in this version included the following:
 List comprehension.
 Cycle-detecting garbage collector.
 Support for Unicode.
 Unification of data types and classes.
12.2008 Python 3.0
The work on this version began back in 2000. Developers wanted to
streamline the language and eliminate unnecessary language
constructs and functions that had accumulated during almost 20 years
of Python's existence.
Python 3.0 was backward-incompatible and brought some unexpected
complications. It turned out Python was being widely used and often
depended on other Python libraries. While it was easy to move one's
scripts to Python 3, it was much harder to move programs that relied
on third-party libraries since they didn't upgrade quickly.
Even with all the difficulties, the improvements in this version were
important. The features implemented in Python 3.0 included the
following:
 The print keyword was changed to the print() function.
 The raw_input() function was deprecated.
 It unified the str and unicode types.
 It included utilities for automatic conversion of Python 2.x code.
The migration from Python 2 was finally completed with its retirement in 2020.

10.2020 Python 3.9


The rapid growth of Python's popularity began in 2010. Soon, Python
was competing with the most popular languages like Java and
JavaScript.
Other features have been implemented in this current version of
Python:
 Dictionary merge and mpdate operators.
 New removeprefix() and removesuffix() string methods.
 Built-in generic types.
Python's popularity grew with the rise of fields such as machine
learning and Big Data. But it owes much of its position to the number of
developers using Python in their everyday work.

Libraries and Frameworks


Python is very popular for many things, and one of them is its
extensibility. The evolution of Python includes the emergence of some
tools without which it would not exist. If you have started or are
interested in learning Python, you may have already heard about its
libraries and frameworks.
Python has thousands of LIBRARIES that contain packages to
perform specific operations. Developers can find reusable chunks of
code in libraries to reduce the number of lines in their own code.
Some of the most popular libraries are:
 This is an open-source library for deep-learning applications built
by the Google Brain Team. The initial version was released in
2015 under Apache License 2.0.
 NumPy, or Numerical Python. Created by Travis Oliphant in 2015,
it is a key library for scientific and mathematical computing.
 Initially released in 2008, this data manipulation and analysis tool
was created by Wes McKinney.
Frameworks are usually more complex than libraries. They contain the
basic flow and architecture of an application.
There are many popular web frameworks for Python. Here are some of
them:
 A web framework that makes it easier to build better web apps
more quickly and with less code.
 A developer-focused tool with all the features needed for rapid
development, perfect for beginners getting their first web app
deployed.
 A rapid web development web framework for creating a database-
driven, ready-to-extend application in minutes.
If you need more explanation, READ ABOUT THE DIFFERENT CONCEPTS
IN PYTHON HERE. And check out the PYTHON WIKI for more frameworks
and other information about Python.

Python Today
Python is now widely used in many different areas. Web development
is one of them. If you are thinking about a career as a developer, you
can bet you will use Python. Thanks to frameworks like Django and
Flask, Python is a perfect option for quick web development.
Another field where Python is a must-have is machine learning.
Libraries like TensorFlow and Keras provide invaluable support for
machine learning.
Data science has had some of the hottest jobs as of late, and Python
comes in handy here also. Thanks to its simplicity, Python allows
people to LEARN IT QUICKLY EVEN WHEN THEY HAVE NO
PREVIOUS IT EXPERIENCE.
It doesn't look like the current popularity of Python is going to wane
anytime soon. Its wide application and the growing need in the labor
market for specialists with Python skills serve as AN INVITATION
AND A MOTIVATION TO LEARN IT NOW.
If you are not sure if you want to learn Python, start with resources right
at your fingertips. Start on YouTube with some INTERESTING
PYTHON CHANNELS or listen to PYTHON PODCASTS. If you
prefer an old-school approach, reach for one of the PYTHON BOOKS.
There are countless possibilities.
Then, when you are ready, take one of the ONLINE PYTHON
COURSES where you can learn and practice with lots of real-world
examples and activities. The world of Python awaits you!
27.CONDITIONAL STATEMENTS & LOOPS
1.Briefly discuss the difference between if and if-else statement.
ANS:-
if Statement:-
The if statement is used to check if a condition is true. If the condition is true, it runs a
block of code. If the condition is false, it does nothing.
Syntax: if condition:
# Code to execute if condition is True
Example:-
age = 18
if age >= 18: print("You are eligible to vote.")
if-else Statement:-

The if-else statement is used to test a condition and execute one block of code if the
condition is True, and another block of code if the condition is False.

Syntax:

if condition:

# Code to execute if condition is True

else:

# Code to execute if condition is False

Example:-

age = 16

if age >= 18:

print("You are eligible to vote.")

else:

print("You are not eligible to vote.")


2. In which cases, if-elif-else statement is used?

ANS:-

The if-elif-else statement in Python is used when you need to check multiple
conditions and execute different blocks of code based on which condition is true. It's a
way to handle more complex decision-making scenarios.

When to Use if-elif-else Statement

 Multiple Conditions: When you have more than two conditions to check.
 Mutually Exclusive Conditions: When the conditions are mutually exclusive
(i.e., only one condition will be true at a time).
 Clear and Readable Code: When you want to write clear and readable code by
handling different scenarios in a structured way.

Syntax:-

if condition1:

# Code to execute if condition1 is True

elif condition2:

# Code to execute if condition2 is True

elif condition3:

# Code to execute if condition3 is True

else:

# Code to execute if all conditions above are False

3.What is the difference between finite and infinite loop?

ANS:

Finite Loop

A finite loop is a loop that runs a specific number of times. It knows when to stop. Think
of it like a countdown timer that stops when it reaches zero.
Syntax:-

for variable in range(number):

# Code to execute in each iteration

Example:-

for i in range(5):

# This loop runs 5 times (from 0 to 4)

print(i)

Infinite Loop:-

An infinite loop runs forever unless you tell it to stop. We use the while loop for this
purpose.

Syntax:-

while condition:

# Code to execute in each iteration

Example:-

counter = 0

while True:

print("This is loop number", counter)

counter += 1

# Exit the loop after 5 iterations

if counter >= 5:

break
4. Which loop can iterate for infinite number of times and why?

ANS: In Python, a while loop can iterate for an infinite number of times. This
happens when the loop condition always evaluates to True. An infinite loop is created
when the loop condition does not have a terminating condition or stopping point.

Syntax:
while True:

print("This loop will run forever!")


5. Explain the syntax of a for loop.
ANS:
Syntax:-
for variable in sequence:

# Code to execute for each item in the sequence

 variable: This is a temporary variable that takes the value of the current item in
the sequence during each iteration.

 sequence: This is the collection of items you want to iterate over (e.g., a list, tuple,
string, or range).

 Indented Code Block: The code block indented under the for statement is executed
once for each item in the sequence.
Example:-
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:-
apple
banana
cherry
6.Explain nested if statement with an example.

ANS:

A nested if statement in Python is an if statement that is placed inside another if or


else statement. This allows you to check multiple conditions in a hierarchical manner.

Syntax:-

if condition1:

# Code to execute if condition1 is True

if condition2:

# Code to execute if condition2 is True

else:

# Code to execute if condition2 is False

else:

# Code to execute if condition1 is False

Example:

marks = 85

if marks >= 40:

print("You passed the exam!")

if marks >= 75:

print("Congratulations! You got a distinction!")

else:

print("Good job, but no distinction.")

else:

print("You failed the exam. Better luck next time!")


7.Explain the role of break statement in loops with an example.

ANS:

The break statement in Python is used to exit a loop prematurely, regardless of the
loop's natural termination condition. It can be particularly useful when you want to stop
the loop once a certain condition is met, rather than allowing the loop to run to
completion.

Role of break Statement:

 Immediate Termination: The break statement immediately terminates the loop


in which it is present.
 Control Flow: It provides finer control over the flow of the program, enabling the
loop to be exited based on specific conditions.
 Performance Optimization: It can be used to avoid unnecessary iterations,
improving the performance of the program.

Example:-

numbers = [1, 3, 5, 7, 9, 11, 13, 15]

search_for = 9

for number in numbers:

if number == search_for:

print(f"Found the number {search_for}!")

break # Exit the loop as soon as the number is found

print(f"Checking number {number}")

print("Loop has exited.")

Explanation:

1. Loop through List: The for loop iterates through each number in the list
numbers.
2. Condition Check: Inside the loop, the if statement checks if the current
number is equal to the search_for number.
3. Break Statement: When the number is found, the print statement displays a
message, and the break statement is executed to exit the loop immediately.
4. Termination: After the break statement, the loop stops running, and the
program moves to the next line after the loop, printing "Loop has exited."

8.Explain the effect of continue statement in while loop.

ANS:

The continue statement in a while loop is used to skip the rest of the code inside
the loop for the current iteration and move to the next iteration immediately. When the
continue statement is encountered, the loop does not terminate but continues with the
next iteration.

Effect of continue Statement:

 Skips to the Next Iteration: The continue statement causes the loop to skip the
rest of the code inside the loop for the current iteration and jump to the next
iteration.
 Does Not Exit the Loop: Unlike the break statement, continue does not exit
the loop; it just skips the remaining code for that particular iteration.

Example:-
number = 0
while number <= 10:
number += 1
# Skip the rest of the code if the number is odd
if number % 2 != 0:
continue
print(number)
Explanation:

 Initialize number: The variable number is initialized to 0.

 While Loop Condition: The loop runs as long as number is less than or equal to 10.

 Increment number: The variable number is incremented by 1 in each iteration.


 Check for Odd Numbers: If number is odd (number % 2 != 0), the
continue statement is executed, which skips the print(number) statement and
jumps to the next iteration.

 Print Even Numbers: If number is even, it gets printed.

OUTPUT:-

2,4,6,8,10

9.How can pass statement effect the iterations of a for loop?


ANS:

The pass statement in Python is a null statement; it does nothing when executed. It's
often used as a placeholder in loops, functions, classes, or conditional statements when
you haven't written the actual code yet but want to maintain the structure of your
program.

Effect of pass Statement in a for Loop:

 The pass statement allows the loop to iterate over all items without performing
any actions during the iterations.
 It essentially tells Python to "do nothing" and move to the next iteration of the
loop.

Syntax:
for variable in sequence:
pass # Does nothing and moves to the next iteration
Example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
pass # Do nothing for even numbers
else:
print(number)
Explanation:

1. The for loop iterates over each number in the numbers list.
2. The if statement checks if the number is even (number % 2 == 0).
3. If the number is even, the pass statement is executed, which does nothing and
moves to the next iteration.
4. If the number is odd, the print(number) statement is executed, printing the
number.

10. Explain how to combine range() function with for loop to iterate 10 times.

ANS:

Combining the range() function with a for loop is a common way to repeat a block
of code a specific number of times. The range() function generates a sequence of
numbers, which the for loop can iterate over. Here's how you can use it to iterate 10
times:

Syntax:-

for variable in range(10):

# Code to execute 10 times

Example:-

for i in range(10):

print(i)

Explanation:

1. range(10): This generates a sequence of numbers from 0 to 9.


2. for i in range(10): The for loop iterates over each number in the sequence.
3. print(i): This prints the current value of i in each iteration.

Output:-
0123456789
28.STRINGS AND LISTS
1) What is a string and how to define it?
ANS:

A string in Python is a sequence of characters enclosed in quotes. Strings can be created using single
quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """..."""). They are
commonly used to represent text.

Example: name = “I am string” or ‘I am string’ or “’I am string’”


2) How to create multiline string? Explain with an example.

ANS:
Creating a multiline string in Python is straightforward and can be done using triple quotes
('''...''' or """..."""). This allows you to span your string across multiple lines, making it easier
to read and write long texts.

How to Create a Multiline String :

1. Using Triple Single Quotes ('''...'''):

multiline_string = '''This is a multiline string.

It can span multiple lines.

You can write text freely across different lines.'''

2. Using Triple Double Quotes ("""..."""):

multiline_string = """This is another example of a multiline string.

It works the same way as triple single quotes.

You can use it to write text across multiple lines."""

3. What is strig slicing ? How can we slice the last 3 characters of a string?

ANS:
String slicing in Python is a technique used to extract a specific portion of a string by specifying a
range of indices. It allows you to create a substring by defining the start and end positions within the
original string.

The syntax for slicing is:


substring = original_string[start:end]

Example:

text = "Hello, world!"

substring = text[0:5]

print(substring)

Output: Hello

4) How can we escape single and double quotes in string declaration?

ANS:

To escape single and double quotes in string declarations in Python, you can use the
backslash (\) escape character.

Example: single_quote_string = 'It\'s a beautiful day!'

print(single_quote_string)

# Output: It's a beautiful day!

5) Explain the positive and negative index for a string.

ANS:
In Python, strings are sequences of characters, and each character in a string has an index.
Python supports both positive and negative indexing to access characters in a string.
Let's break it down:
Positive Indexing:

 Positive indexing starts from 0 and goes up to the length of the string minus one.
 The first character of the string has an index of 0, the second character has an index of 1, and
so on.

Example:

text = "Hello, world!"


# Positive Indexing:
#H e l l o , w o r l d !
# 0 1 2 3 4 5 6 7 8 9 10 11 12
print(text[0]) # Output: H
print(text[7]) # Output: w
Negative Indexing:

 Negative indexing starts from -1 and goes down to the negative of the length of the string.
 The last character of the string has an index of -1, the second to last character has an index
of -2, and so on.

Example:

text = "Hello, world!"


# Negative Indexing:
#H e l l o , w o r l d !
#-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(text[-1]) # Output: !
print(text[-7]) # Output: w
6) How can we replicate a string? Explain by replicating “Name “5 times.
ANS:
Replicating a string in Python is simple and can be done using the multiplication operator ( *). This
allows you to repeat the string a specified number of times.
Syntax: repeated_string = original_string * n
Example: str1=”Name”
Replicated_str1=str1*5
Output: Name Name Name Name Name
7) What is string concatenation? Explain by concatenating 3 strings.
ANS:
String concatenation is the process of joining two or more strings together to form a single string.
It's like gluing pieces of text together end-to-end.
Let's go through an example:

string1 = "Hello, "


string2 = "world"
string3 = "!"
result = string1 + string2 + string3
print(result)
# Output: Hello, world!
8) When are two strings equal?
ANS:
Two strings are considered equal when they have the exact same sequence of characters, including
the same length and order of characters. This means that every character in one string must match
the corresponding character in the other string.
Example:
string1 = "hello"
string2 = "hello"
print(string1 == string2) # Output: True

string3 = "Hello"
print(string1 == string3) # Output: False
9) Explain the method used to convert a string into upper case with an example.
ANS:
Converting a string to uppercase means changing all the letters in the string to their uppercase form.
Most programming languages offer built-in methods for this. Let's take Python as an example.

In Python, you can use the upper() method to convert a string to uppercase. Here's how it works:

Example:

# Original string
original_string = "Hello, World!"

# Convert to uppercase
uppercase_string = original_string.upper()

print(uppercase_string) # Output: HELLO, WORLD!

10) How to find the length of a string? Find the length of string “This is a long string”.
ANS:
To find the length of a string, you can use the built-in len() function in Python. The len() function
returns the number of characters in a string, including spaces and punctuation.

Here's how you can use it to find the length of the string "This is a long string":

# Given string
string = "This is a long string"
# Find the length of the string
length_of_string = len(string)
print(length_of_string)
# Output: 21
11) When should we use lists in python?
ANS:
Lists in Python are incredibly versatile and can be used in various scenarios. Here are some key
situations where you might want to use a list:

1.Storing Multiple Items:


2.Ordered Data:
3. Mutable Data:
4. Iterating Over Elements:
5. Nested Lists:
6. Dynamic Arrays:
12) Explain two different ways of creating a list in Python.
ANS:
There are several ways to create a list in Python. Here are two common methods:

1. Using Square Brackets []


This is the most straightforward and commonly used method to create a list. You simply enclose the
elements in square brackets, separated by commas.
Example:
# Creating a list using square brackets
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]

2. Using the list() Constructor


The list() constructor can be used to create a list from any iterable (e.g., a string, a tuple, or
another list). It is particularly useful when converting other data types to a list.
Examples:
# Creating an empty list
empty_list = list()
print(empty_list) # Output: []

# Creating a list from a string


string = "hello"
string_list = list(string)
print(string_list) # Output: ['h', 'e', 'l', 'l', 'o']

# Creating a list from a tuple


tuple_data = (1, 2, 3)
tuple_list = list(tuple_data)
print(tuple_list) # Output: [1, 2, 3]

13) What is empty list? Can this list be filled with elements later?
ANS:
An empty list is a list that contains no elements. You can create an empty list using square brackets
[] or the list() constructor in Python. Here are examples of both methods:
Example:
# Creating an empty list using square brackets
empty_list1 = []

# Creating an empty list using the list() constructor


empty_list2 = list()

print(empty_list1) # Output: []
print(empty_list2) # Output: []
14) How to traverse through the different elements of a list? Create a list of 5
elements and display its third element.
ANS:
To traverse through the elements of a list, you can use loops such as for or while loops. Here’s an
example using a for loop:
# Creating a list with 5 elements
my_list = [10, 20, 30, 40, 50]

# Traversing through the list and printing each element


print("Traversing the list:")
for element in my_list:
print(element)

# Displaying the third element (index 2)


third_element = my_list[2]
print("\nThird element of the list:")
print(third_element)

# Output: 30

15) What is list concatenation? Explain by concatenating 3 lists using a


Python program.
ANS:
List concatenation in Python refers to joining two or more lists together to create a single combined
list. This can be done using the + operator or the extend() method. Let me demonstrate this with
an example using the + operator to concatenate three lists:
Example:
# Define three lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

# Concatenate the lists using the + operator


combined_list = list1 + list2 + list3

# Print the combined list


print("Combined List:", combined_list)

Out-put:
Combined List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
16) Explain how we can slice the first 3 elements of a list with more than 3 elements.
ANS:
Slicing in Python is a way to extract a portion of a list using a colon : to specify the start and end
indices. To slice the first three elements of a list, you can use the following syntax:
# Define a list with more than 3 elements
my_list = [10, 20, 30, 40, 50, 60]

# Slice the first 3 elements


first_three_elements = my_list[:3]

# Print the sliced list


print("First 3 elements:", first_three_elements)
OUT-PUT:
First 3 elements: [10, 20, 30]

17) How to check if an element is present in a list or not?


ANS:
In Python, you can check if an element is present in a list using the in keyword. Here's an example:

# Define a list
my_list = [10, 20, 30, 40, 50]

# Check if an element is present in the list


element_to_check = 30

# Using the 'in' keyword


is_present = element_to_check in my_list

# Print the result


print(f"Is {element_to_check} present in the list? {is_present}")

OUT-PUT:
Is 30 present in the list? True

18) Explain the insert () function by inserting 2 new elements to an


existing list.
ANS:
In Python, the insert() function is used to add a new element at a specific index in a list. Here's
an example of how to use insert() to add two new elements to an existing list:
# Define an existing list
my_list = [10, 20, 30, 40, 50]

# Insert a new element at index 1


my_list.insert(1, 15)

# Insert another new element at index 4


my_list.insert(4, 35)

# Print the updated list


print("Updated List:", my_list)

OUT-PUT:
Updated List: [10, 15, 20, 30, 35, 40, 50]

19) How does remove () function work in lists?


ANS:
The remove() function in Python is used to remove the first occurrence of a specified element from
a list. If the element is not found in the list, it raises a ValueError. Here's an example to illustrate
how it works:
# Define a list
my_list = [10, 20, 30, 40, 50, 30]

# Remove the first occurrence of the element 30


my_list.remove(30)

# Print the updated list


print("Updated List:", my_list)

OUT-PUT:
Updated List: [10, 20, 40, 50, 30]

20) How can we create a copy of existing list?


ANS:
There are several ways to create a copy of an existing list in Python. Here are a few common
methods:
1. Using the copy() Method
2. Using Slicing
3. Using the list() Function
4. Using the deepcopy() Function (for Nested Lists)
21) Which function is used to find the maximum and minimum valued elements
in a lists?
ANS:
In Python, you can use the built-in functions:
max() to find the maximum-valued element in a list.
min() to find the minimum-valued element in a list.
22) Explain the sum() function used in lists.
ANS:
sum() Function in Python Lists
The sum() function in Python is used to calculate the sum of all elements in a list (or any iterable)
containing numerical values.
Syntax:
sum(iterable, start)

 iterable: The list (or other iterable) containing numbers.


 start (optional): A value to add to the sum. Default is 0.

You might also like