Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

Python Module 2 (YouTube Manoj P N)

Uploaded by

syedfarhan3599
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Python Module 2 (YouTube Manoj P N)

Uploaded by

syedfarhan3599
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python module 2 for IA

1. Explain the methods of List data type in Python for the following operations
with suitable code snippets for each.
(i) Adding values to a list ii) Removing values from a list
(iii) Finding a value in a list iv) Sorting the values in a list

ANS:
Python lists:

The list is a built-in data type used to store collections of items. Lists are one of
the most versatile and commonly used data structures in Python. They are used to
hold an ordered collection of elements, and these elements can be of any data
type, including numbers, strings, other lists, or even more complex objects. Lists
are mutable, which means you can change their contents by adding, removing, or
modifying elements.

(i) Adding Values to a List:

You can add values to a list using various methods:

Append: The append() method adds an element to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
# Resulting list: [1, 2, 3, 4]
Insert: The insert() method inserts an element at a specific index in the list.
Example:
my_list = [1, 2, 3]
my_list.insert(1, 4) # Insert 4 at index 1
# Resulting list: [1, 4, 2, 3]
(ii) Removing Values from a List:

You can remove values from a list using these methods:

Remove: The remove() method removes the first occurrence of a specified value.
Example:
my_list = [1, 2, 3, 2]
my_list.remove(2) # Removes the first occurrence of 2
# Resulting list: [1, 3, 2]

Pop: The pop() method removes and returns the element at a specified index. If no
index is provided, it removes and returns the last element.
Example:
my_list = [1, 2, 3]
value = my_list.pop(1) # Removes and returns the element at index 1 (2)
# Resulting list: [1, 3], value: 2
Del Statement: The del statement can delete elements by index or even the
entire list.
Example:
my_list = [1, 2, 3]
del my_list[1] # Deletes element at index 1 (2)
# Resulting list: [1, 3]

my_list = [1, 2, 3]
del my_list # Deletes the entire list
# Results in an error if you try to access my_list afterward
(iii) Finding a Value in a List:

To find a value in a list, you can use the in operator or the index() method:

Using in Operator:
Example:
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
print("3 is in the list.")
Using index() Method:
Example:
Copy codmy_list = [1, 2, 3, 4, 5]
index = my_list.index(3) # Returns the index of the first occurrence of 3
print("Index of 3:", index)

(iv) Sorting the Values in a List:

You can sort a list in ascending or descending order:

Sort in Ascending Order:


Example:
my_list = [3, 1, 4, 2]
my_list.sort()
# Resulting list: [1, 2, 3, 4]
Sort in Descending Order:
Example:
my_list = [3, 1, 4, 2]
my_list.sort(reverse=True)
# Resulting list: [4, 3, 2, 1]
You can also create a sorted copy of the list without modifying the original using
the sorted() function:
Example:
my_list = [3, 1, 4, 2]
sorted_list = sorted(my_list)
# Resulting list: [1, 2, 3, 4]
These methods and operations provide flexibility when working with lists in Python,
allowing you to add, remove, find, and sort values according to your needs.

2.What is a list? Explain append(), insert(),index() and remove() methods with


examples, also list down differences between list and tuple and how list can be
converted to tuple-10 marks Qn 🤩
ANS:
What is a List?:

A list in Python is a built-in data structure that represents an ordered collection of


items. Lists are mutable, which means their contents can be modified after
creation. Each item in a list is called an element, and elements can be of different
data types, including numbers, strings, and even other lists.

List Methods:

append() Method:

append() adds an element to the end of the list.


Syntax: list.append(element)
Example:
my_list = [1, 2, 3]
my_list.append(4)
# Resulting list: [1, 2, 3, 4]
insert() Method:

insert() inserts an element at a specified index in the list.


Syntax: list.insert(index, element)
Example:
my_list = [1, 2, 4]
my_list.insert(2, 3) # Insert 3 at index 2
# Resulting list: [1, 2, 3, 4]
index() Method:

index() returns the index of the first occurrence of a specified element in the list.
Syntax: list.index(element)
Example:
my_list = [10, 20, 30, 20, 40]
index = my_list.index(20) # Returns the index of the first 20 (1)
remove() Method:

remove() removes the first occurrence of a specified element from the list.
Syntax: list.remove(element)
Example:
my_list = [10, 20, 30, 20, 40]
my_list.remove(20) # Removes the first 20
# Resulting list: [10, 30, 20, 40]
Differences Between List and Tuple:

Mutability:
List: Lists are mutable, which means you can change their contents (add, remove, or
modify elements).

Tuple: Tuples are immutable, and their contents cannot be modified once created.
Syntax:

List: Created using square brackets, e.g., [1, 2, 3].


Tuple: Created using parentheses, e.g., (1, 2, 3).
Performance:

List operations may be slightly slower due to mutability.


Tuple operations can be faster because of immutability.
Use Case:

Lists are used for collections of items where elements can change or need to be
modified.
Tuples are used for collections that should not change, like coordinates or records.
Converting a List to a Tuple:

To convert a list to a tuple in Python, you can use the tuple() constructor, passing
the list as an argument. Here's an example:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
# my_list is [1, 2, 3], and my_tuple is (1, 2, 3)
This creates a new tuple with the same elements as the original list. The resulting
tuple is immutable, and its elements cannot be changed.

3.What is a string? Explain any four methods associated with string and
explain each of them with an example.

ANS:

What is a String?:

In Python, a string is a built-in data type used to represent text, characters, or


sequences of characters. Strings are enclosed in either single (') or double (")
quotation marks and are widely used for manipulating and representing textual
data. Python provides a range of methods to work with strings.

Here are four common string methods along with explanations and examples:

1. len() Method:

The len() method is used to get the length (the number of characters) of a string.

Syntax: len(string)
Example:
text = "Hello, World!"
length = len(text)
print(length) # Output: 13
2. upper() Method:

The upper() method converts all characters in a string to uppercase.


Syntax: string.upper()
Example:
text = "Hello, World!"
uppercase_text = text.upper()
print(uppercase_text) # Output: "HELLO, WORLD!"
3. lower() Method:

The lower() method converts all characters in a string to lowercase.

Syntax: string.lower()
Example:
text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text) # Output: "hello, world!"
4. replace() Method:

The replace() method replaces occurrences of a specified substring with another


string.

Syntax: string.replace(old, new)


Example:
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text) # Output: "Hello, Python!"
These methods are just a few examples of the many string methods available in
Python. They allow you to perform various operations on strings, such as finding
lengths, changing cases, and replacing substrings, making string manipulation a
fundamental part of many Python applications.

4.Discuss the different ways of traversing a list. Explain each with an


example

ANS:
Traversing a list means visiting each element of the list to perform some
operation, such as printing, modifying, or searching. There are several ways to
traverse a list in Python.

1. Using a For Loop:

You can use a for loop to iterate through the elements of a list one by one.

Example:
my_list = [1, 2, 3, 4, 5]

for item in my_list:


print(item)
In this example, the for loop iterates through my_list, and each element is stored
in the item variable and printed.

2. Using a While Loop with Index:

You can use a while loop along with an index to traverse a list.

Example:
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
In this example, a while loop is used with an index variable to iterate through
my_list. The loop continues until the index reaches the length of the list.

3. Using List Comprehension:

List comprehension is a concise way to traverse a list and perform an operation on


each element. It creates a new list based on the existing one.

Example:
my_list = [1, 2, 3, 4, 5]

squared_list = [item**2 for item in my_list]


print(squared_list)
In this example, a new list squared_list is created by squaring each element in
my_list.

4. Using Enumerate:

The enumerate() function can be used to traverse a list while keeping track of the
index.

Example:
my_list = [10, 20, 30, 40, 50]

for index, value in enumerate(my_list):


print(f"Index {index}: {value}")
In this example, the enumerate() function provides both the index and the value of
each element.

5. Using a For Loop with Range:


You can also use a for loop in combination with the range() function to traverse a
list by index.

Example:
my_list = [1, 2, 3, 4, 5]

for index in range(len(my_list)):


print(my_list[index])
In this example, the range() function generates indices, and the for loop accesses
the list elements by index.

5. What is a Dictionary in Python? How is it different from List data


type?Discuss the following Dictionary methods in Python with examples.
(i) get() (ii) items() (iii) keys() (iv) values()

ANS:
A dictionary in Python is a built-in data type that represents an unordered
collection of key-value pairs. It is also known as an associative array or a hash map.
Dictionaries are used to store and retrieve data based on keys rather than indices.
Each key in a dictionary maps to a specific value, and you can use keys to access,
modify, and delete values in the dictionary. Dictionaries are enclosed in curly
braces {} and consist of key-value pairs separated by colons.

Differences Between Dictionary and List:

List:

Ordered collection of items accessed by index.


Elements can be of any data type.
Elements are stored in a specific order.
Use square brackets [ ] to create lists.
Dictionary:
Unordered collection of key-value pairs accessed by keys.
Keys and values can be of any data type.
Elements are stored in no specific order.
Use curly braces { } to create dictionaries.

Dictionary Methods:

get() Method:

The get() method retrieves the value associated with a specified key. It allows you
to provide a default value if the key doesn't exist in the dictionary.
Syntax: dictionary.get(key, default_value)

Example:

student_scores = {"Alice": 90, "Bob": 85, "Charlie": 88}


score = student_scores.get("Bob", 0) # Returns 85 (key exists)
absent_score = student_scores.get("David", 0) # Returns 0 (key doesn't exist)
items() Method:

The items() method returns a view of all key-value pairs in the dictionary as tuples.
Syntax: dictionary.items()

Example:
student_scores = {"Alice": 90, "Bob": 85, "Charlie": 88}
score_pairs = student_scores.items()
# Returns a view: dict_items([('Alice', 90), ('Bob', 85), ('Charlie', 88)])
keys() Method:

The keys() method returns a view of all keys in the dictionary.


Syntax: dictionary.keys()
Example:
student_scores = {"Alice": 90, "Bob": 85, "Charlie": 88}
keys = student_scores.keys()
# Returns a view: dict_keys(['Alice', 'Bob', 'Charlie'])
values() Method:

The values() method returns a view of all values in the dictionary.


Syntax: dictionary.values()
Example:

student_scores = {"Alice": 90, "Bob": 85, "Charlie": 88}


scores = student_scores.values()
# Returns a view: dict_values([90, 85, 88])

These dictionary methods provide convenient ways to access and manipulate


key-value pairs in dictionaries. You can use them for tasks like retrieving values,
iterating over keys and values, and more.

6. Compare list and dictionary data structures with respect to python


language.

You might also like