Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit - 2 (5m)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

Unit -2 (5m):
Explain the different list methods with an example.

In Python, a list is a mutable sequence of elements that can be


modified after it is created. There are several built-in list methods that
can be used to manipulate and transform lists. Here are some
commonly used list methods with examples:

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

lessCopy code # Define a sample list fruits = ["apple", "ban


ana", "cherry"] # Append a new fruit to the list fruits.appe
nd("orange") print(fruits) # Output: ["apple", "banana", "ch
erry", "orange"]

1. insert() : Inserts an element at a specified position in a list.

lessCopy code # Define a sample list fruits = ["apple", "ban


ana", "cherry"] # Insert a new fruit at the second position
in the list fruits.insert(1, "orange") print(fruits) # Outpu
t: ["apple", "orange", "banana", "cherry"]

1. remove() : Removes the first occurrence of an element from a list.

pythonCopy code # Define a sample list fruits = ["apple", "b


anana", "cherry"] # Remove the "banana" fruit from the list
fruits.remove("banana") print(fruits) # Output: ["apple", "c
herry"]

1. pop() : Removes and returns the element at a specified position


in a list.

pythonCopy code # Define a sample list fruits = ["apple", "b


anana", "cherry"] # Remove and return the element at the sec
ond position in the list removed_fruit = fruits pop(1) print

1 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

ond position in the list removed_fruit = fruits.pop(1) print


(fruits) # Output: ["apple", "cherry"] print(removed_fruit)
# Output: "banana"

1. sort() : Sorts the elements in a list in ascending order.

pythonCopy code # Define a sample list numbers = [3, 1, 4,


1, 5, 9, 2, 6, 5, 3, 5] # Sort the numbers in ascending orde
r numbers.sort() print(numbers) # Output: [1, 1, 2, 3, 3, 4,
5, 5, 5, 6, 9]

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

perlCopy code # Define a sample list fruits = ["apple", "ban


ana", "cherry"] # Reverse the order of the fruits in the lis
t fruits.reverse() print(fruits) # Output: ["cherry", "banan
a", "apple"]

1. index() : Returns the index of the first occurrence of an element


in a list.

perlCopy code # Define a sample list fruits = ["apple", "ban


ana", "cherry", "banana", "apple"] # Find the index of the f
irst occurrence of "banana" in the list index = fruits.index
("banana") print(index) # Output: 1

These are just some of the commonly used list methods in Python.
There are many other list methods available that can be used to
manipulate and transform lists according to your specific needs.
Explain the ways of indexing and slicing the list with examples.

Indexing and slicing are powerful features of lists in Python that allow
you to access and manipulate specific elements in a list. Here are the
ways of indexing and slicing a list with examples:

1. Indexing a list:

2 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

You can access an element in a list using its index. The first element in
a list has an index of 0, the second element has an index of 1, and so
on. Here's an example:

makefileCopy code # Define a sample list fruits = ["apple",


"banana", "cherry"] # Access the first element in the list u
sing its index first_fruit = fruits[0] print(first_fruit) #
Output: "apple"

1. Slicing a list:
You can extract a portion of a list by slicing it. To slice a list, you need
to specify the start index and end index of the portion you want to
extract. The start index is inclusive, while the end index is exclusive.
Here's an example:

lessCopy code # Define a sample list fruits = ["apple", "ban


ana", "cherry", "date", "elderberry"] # Extract a portion of
the list using slicing portion = fruits[1:4] print(portion)
# Output: ["banana", "cherry", "date"]

In the example above, the slicing operation extracts elements with


indices 1, 2, and 3 (i.e., "banana", "cherry", and "date").

You can also use negative indices to index and slice a list from the
end. For example:

makefileCopy code # Define a sample list fruits = ["apple",


"banana", "cherry", "date", "elderberry"] # Access the last
element in the list using a negative index last_fruit = frui
ts[-1] print(last_fruit) # Output: "elderberry" # Extract a
portion of the list from the end using negative indices port
ion = fruits[-4:-1] print(portion) # Output: ["cherry", "dat
e", "elderberry"]

In the example above, the slicing operation extracts elements with


indices -4, -3, and -2 (i.e., "cherry", "date", and "elderberry"). Note that

3 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

the slice excludes the element with index -1, which is "elderberry".

Overall, indexing and slicing are powerful features of lists in Python


that can be used to access and manipulate specific elements or
portions of a list according to your specific needs.
Explain the built-in functions used in a dictionary.

Python provides a number of built-in functions that can be used on


dictionaries. Here are some of the most commonly used functions:

1. len() : This function returns the number of key-value pairs in a


dictionary. Example:

pythonCopy code my_dict = {"apple": 2, "banana": 3, "cherr


y": 5} print(len(my_dict)) # Output: 3

1. dict() : This function creates a new dictionary. You can pass key-
value pairs as arguments to create a dictionary, or you can pass a
sequence of key-value pairs as an argument to create a dictionary.
Example:

scssCopy code my_dict = dict(apple=2, banana=3, cherry=5) pr


int(my_dict) # Output: {"apple": 2, "banana": 3, "cherry":
5} my_dict = dict([("apple", 2), ("banana", 3), ("cherry",
5)]) print(my_dict) # Output: {"apple": 2, "banana": 3, "che
rry": 5}

1. sorted() : This function returns a new list of the keys in a


dictionary in sorted order. Example:

scssCopy code my_dict = {"apple": 2, "banana": 3, "cherry":


5} sorted_keys = sorted(my_dict) print(sorted_keys) # Outpu
t: ["apple", "banana", "cherry"]

1. keys() : This function returns a new list of the keys in a dictionary.


Example:

4 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

scssCopy code my_dict = {"apple": 2, "banana": 3, "cherry":


5} my_keys = my_dict.keys() print(my_keys) # Output: dict_ke
ys(["apple", "banana", "cherry"])

1. values() : This function returns a new list of the values in a


dictionary. Example:

makefileCopy code my_dict = {"apple": 2, "banana": 3, "cherr


y": 5} my_values = my_dict.values() print(my_values) # Outpu
t: dict_values([2, 3, 5])

1. items() : This function returns a new list of the key-value pairs in


a dictionary as tuples. Example:

scssCopy code my_dict = {"apple": 2, "banana": 3, "cherry":


5} my_items = my_dict.items() print(my_items) # Output: dict
_items([("apple", 2), ("banana", 3), ("cherry", 5)])

Overall, these built-in functions provide a convenient way to


manipulate and analyze dictionaries in Python.
Explain tuple methods with examples.

Tuples are similar to lists in Python, but they are immutable, meaning
their values cannot be modified. Here are some of the commonly
used tuple methods in Python:

1. count() : This method returns the number of times a specified


element appears in a tuple. Example:

my_tuple = (1, 2, 3, 2, 4, 5, 2) count = my_tuple.count(2) p


rint(count) # Output: 3

1. index() : This method returns the index of the first occurrence of


a specified element in a tuple. Example:

5 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

perlCopy code my_tuple = (1, 2, 3, 2, 4, 5, 2) index = my_tu


ple.index(4) print(index) # Output: 4

1. len() : This function returns the number of elements in a tuple.


Example:

scssCopy code my_tuple = (1, 2, 3, 2, 4, 5, 2) length = len


(my_tuple) print(length) # Output: 7

1. sorted() : This function returns a new sorted list from the


elements in a tuple. Example:

scssCopy code my_tuple = (4, 2, 5, 1, 3) sorted_list = sorte


d(my_tuple) print(sorted_list) # Output: [1, 2, 3, 4, 5]

1. max() : This function returns the largest element in a tuple.


Example:

scssCopy code my_tuple = (4, 2, 5, 1, 3) largest_element = m


ax(my_tuple) print(largest_element) # Output: 5

1. min() : This function returns the smallest element in a tuple.


Example:

scssCopy code my_tuple = (4, 2, 5, 1, 3) smallest_element =


min(my_tuple) print(smallest_element) # Output: 1

Overall, these tuple methods provide a convenient way to work with


tuples in Python, making them useful in various programming tasks.
Explain any 5 methods used in the dictionary.

In Python, dictionaries are an important data structure used to store

6 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

key-value pairs. Here are five commonly used dictionary methods:

1. keys() : This method returns a list of all the keys in a dictionary.


Example:

my_dict = {'a': 1, 'b': 2, 'c': 3} keys = my_dict.keys() pri


nt(keys) # Output: ['a', 'b', 'c']

1. values() : This method returns a list of all the values in a


dictionary. Example:

my_dict = {'a': 1, 'b': 2, 'c': 3} values = my_dict.values()


print(values) # Output: [1, 2, 3]

1. items() : This method returns a list of all the key-value pairs in a


dictionary as tuples. Example:

my_dict = {'a': 1, 'b': 2, 'c': 3} items = my_dict.items() p


rint(items) # Output: [('a', 1), ('b', 2), ('c', 3)]

1. get() : This method returns the value for a specified key in a


dictionary. If the key is not found, it returns a default value (which
is None by default). Example:

my_dict = {'a': 1, 'b': 2, 'c': 3} value1 = my_dict.get('b')


value2 = my_dict.get('d', 0) print(value1) # Output: 2 print
(value2) # Output: 0

1. update() : This method updates a dictionary with key-value pairs


from another dictionary or an iterable. If a key already exists, its
value is updated; otherwise, a new key-value pair is added.
Example:

my_dict1 = {'a': 1 'b': 2 'c': 3} my_dict2 = {'b': 4 'd':

7 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

my_dict1 = {'a': 1, 'b': 2, 'c': 3} my_dict2 = {'b': 4, 'd':


5} my_dict1.update(my_dict2) print(my_dict1) # Output: {'a':
1, 'b': 4, 'c': 3, 'd': 5}

These dictionary methods are useful in various programming tasks,


such as retrieving values by key, iterating over keys or values, or
updating a dictionary with new values.
Explain the relation between tuples and lists in Python.

In Python, lists and tuples are both used to store collections of values.
However, there are some key differences between the two data
structures:

1. Mutability: Lists are mutable, which means that their contents can
be changed after they are created, whereas tuples are immutable,
which means that their contents cannot be changed once they are
created.

2. Syntax: Lists are enclosed in square brackets [ ] , while tuples are


enclosed in parentheses ( ) .

Here's an example of creating and modifying a list:

my_list = [1, 2, 3] my_list.append(4) print(my_list) # Outpu


t: [1, 2, 3, 4]

And here's an example of creating and modifying a tuple:

my_tuple = (1, 2, 3) new_tuple = my_tuple + (4,) print(new_t


uple) # Output: (1, 2, 3, 4)

Note that in the second example, we had to create a new tuple with
the updated contents instead of modifying the original tuple directly.

Despite these differences, lists and tuples share some similarities:

1. Indexing: Both lists and tuples allow you to access their elements
by index, using the same syntax: my_list[index] or
my_tuple[index] .

8 of 17 12-12-2023, 19:10
Unit -2 (5m): https://awaisahmed.notion.site/Unit-2-5m-9646c91f2a0143b68ea12f54...

2. Iteration: You can iterate over both lists and tuples using a for
loop.

3. Length: Both lists and tuples have a len() function that returns
the number of elements in the collection.

In summary, lists are mutable and enclosed in square brackets, while


tuples are immutable and enclosed in parentheses. Both can be
accessed by index, iterated over with a for loop, and have a len()
function. Choosing between a list and a tuple depends on the specific
needs of your program. If you need to modify the contents of the
collection, use a list. If you need an immutable collection for storing
data, use a tuple.

9 of 17 12-12-2023, 19:10

You might also like