1. How slicing is performed in list with example?
List slicing is a technique used to access a range of elements in a list. It creates a new
list from an old one. The syntax for list slicing is [start:stop:step], where start is the
index of the list where slicing starts, stop is the index of the list where slicing ends,
and step allows you to select every nth item within the range start to stop.
Eg: List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Display sliced list
print(List[3:9:2]) # Output: [4, 6, 8]
2. Define the concept of list of lists?
A list of lists is a data structure that contains multiple lists as its elements. Each list
within the list of lists can be accessed using its index. This concept is also known as a
nested list.A list of lists is useful for storing and organizing data that has multiple
levels of hierarchy, such as a matrix or a table of data. It is also useful for creating and
handling multi-dimensional structures like nested loops or organizing hierarchical
data.
Eg:
myList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Access the first element of the second sublist
print(myList[1][0]) # Output: 4
3. Define List and how can we access the elements of a list in python
A list in Python is a built-in data type that is used to store a collection of items.
It is an ordered collection of elements, and each element in a list has a unique
position index, starting from 0
. Lists are mutable, meaning that you can add, remove, or modify elements in a
list. To access elements in a list in Python, you can use indexing. The index of
the first element in a list is 0, the second element is 1, and so on. You can also
use negative indexing to access elements from the end of the list. For example,
myList[-1] will return the last element of the list
myList = [1, 2, 3, 4, 5]
# Access the first element of the list
print(myList[0]) # Output: 1
# Access the third element of the list
print(myList[2]) #Output 3
4. Write a python code to search an element in a list.
To search an element in a list in Python, there are several ways to achieve this. Here
are some of the most common ways:
1. Using the "in" operator: You can use the "in" operator to check if an element
exists in the list. The "in" operator returns True if the element is found in
the list, and False otherwise.
myList = [1, 2, 3, 4, 5]
# Search for an element in the list
if 3 in myList:
print("Element found")
else:
print("Element not found")
[Link] the index() method: You can use the index() method to find the index of an
element in the list. The index() method returns the index of the first occurrence of the
element in the list
myList = [1, 2, 3, 4, 5]
# Find the index of an element in the list
index = [Link](3)
print("Index of element:", index)
[Link] a for loop: You can use a for loop to iterate through the list and check if the
element exists in the list
myList = [1, 2, 3, 4, 5]
# Search for an element in the list using a for loop
found = False
for element in myList:
if element == 3:
found = True
break
if found:
print("Element found")
else:
print("Element not found")
5. How to create a dictionary for python?
Here are some of the most common methods:
Using curly braces: A dictionary can be created by placing key-value pairs
inside curly braces {}, separated by commas. For example, my_dict = {"key1":
"value1", "key2":
Using the dict() function: An empty dictionary can be created using the dict()
function, or by passing a list of key-value pairs to the function. For example,
my_dict = dict() or my_dict = dict(key1="value1", key2="value2")
Using a dictionary comprehension: A dictionary can be created using a
dictionary comprehension, which is a concise way to create a dictionary from an
iterable. For example, my_dict = {x: x**2 for x in range(5)}
Using the fromkeys() method: A dictionary can be created using the fromkeys()
method, which creates a new dictionary with keys from a given sequence and
values set to a default value. For example, my_dict = [Link](["key1",
"key2"], "default_value")
Using an empty set of curly braces: An empty dictionary can be created by
assigning an empty set of curly braces to a variable. For example, my_dict = {}
6. “List is mutable.” - Justify with suitable example.
A list is a mutable data type in Python, which means that its elements can be modified
after it is created. This is in contrast to immutable data types like strings and tuples,
where the elements cannot be changed once they are created
Here is an example to illustrate the mutability of lists:
my_list = [1, 2, 3, 4]
my_list[2] = 5
print(my_list)
7. Differentiate List and Tuple in Python.
Lists and tuples are two of the most commonly used data structures in Python. While
they share some similarities, there are several key differences between them. Here are
some of the main differences between lists and tuples in Python:
Mutability: The most significant difference between lists and tuples is that lists
are mutable, while tuples are immutable. This means that once a tuple is created,
its elements cannot be modified, whereas the elements of a list can be changed
after it is created
Syntax: Lists are defined using square brackets [], while tuples are defined using
parentheses (). For example, my_list = [1][2][3] and my_tuple = (1, 2, 3)
Memory usage: Tuples are generally more memory-efficient than lists, as they
require less overhead. This is because tuples are immutable, so Python can
allocate memory for them more efficiently
Performance: In general, tuples are faster than lists for certain operations, such
as iterating over the elements. This is because tuples are immutable, so Python
can optimize certain operations for them
Built-in methods: Lists have more built-in methods than tuples, as they are
mutable and can be modified using these methods. Tuples have fewer built-in
methods, as they are immutable and cannot be modified
8. Define reverse lookup
Reverse lookup is a process of finding a key in a dictionary based on its value. In other
words, given a dictionary and a value, the goal is to find the key(s) that correspond to
that value. Reverse lookup is not as straightforward as a regular lookup, where we can
easily find the value of a key.
To perform a reverse lookup in Python, we can use a function that iterates over the
keys and values of a dictionary and returns the first key that maps to the given value.
Here is an example of a function that performs a reverse lookup:
def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
raise LookupError("Value not found in dictionary")
9. What is negative indexes and how they are used in Python?
Negative indexing is a feature in Python that allows accessing elements in a sequence,
such as a list or a string, from the end of the sequence by using negative numbers as
indexes. In Python, the index of the last element in a sequence is -1, the second last is -
2, and so on.
my_list = [1, 2, 3, 4, 5]
To access the last element of the list, we can use the index -1, like this:
last_element = my_list[-1]
[Link] traversing dictionaries.
Traversing a dictionary in Python means iterating over all the key-value pairs in the
dictionary. This is useful when we need to access or modify all the elements in the
dictionary. There are several ways to traverse a dictionary in Python, including using
loops and built-in methods.
One common way to traverse a dictionary is to use a for loop to iterate over the keys
of the dictionary, and then access the corresponding values using the keys. Here is an
example:
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
for key in my_dict:
value = my_dict[key]
print(key, value)
Another way to traverse a dictionary is to use the items() method, which returns a list
of tuples containing the key-value pairs in the dictionary. Here is an example:
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
for key, value in my_dict.items():
print(key, value)
[Link] tuples
A tuple is an ordered collection of elements enclosed in parentheses and
separated by commas. It is a built-in data type in Python, similar to a list, but
with the key difference that tuples are immutable, meaning that their elements
cannot be changed once they are created.
Tuples can contain elements of different data types, including numbers, strings, and other tuples. They can
also be nested, meaning that a tuple can contain other tuples as elements. To create a tuple in Python, we
can enclose a sequence of elements in parentheses, separated by commas. To access elements in a
tuple, we can use indexing, just like with lists. The first element in a tuple has an index of 0, the
second element has an index of 1, and so on.
[Link] sets
A set is a built-in data type in Python that represents an unordered collection of
unique elements. Sets are defined using curly braces {} or the set() function, and
can contain elements of different data types, including numbers, strings, and other
sets. The elements in a set are unordered, meaning that they are not stored in any
particular order, and sets do not allow duplicate elements.
Union: The union of two sets is a new set that contains all the elements from
both sets, without any duplicates. This can be achieved using the union()
method or the | operator. For example, [Link](set2) or set1 | set2 returns
a new set that contains all the elements from set1 and set2
Intersection: The intersection of two sets is a new set that contains only the
elements that are common to both sets. This can be achieved using the
intersection() method or the & operator. For example, [Link](set2)
or set1 & set2 returns a new set that contains only the elements that are in
both set1 and set2
Difference: The difference between two sets is a new set that contains only
the elements that are in the first set but not in the second set. This can be
achieved using the difference() method or the - operator. For example,
[Link](set2) or set1 - set2 returns a new set that contains only the
elements that are in set1 but not in set2
Symmetric difference: The symmetric difference between two sets is a new
set that contains only the elements that are in either of the sets, but not in
both. This can be achieved using the symmetric_difference() method or the ^
operator. For example, set1.symmetric_difference(set2) or set1 ^ set2 returns
a new set that contains only the elements that are in either set1 or set2, but
not in both
[Link] a python code to find transpose of a matrix using list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Get the number of rows and columns
rows = len(matrix)
cols = len(matrix[0])
# Create a new matrix to store the transpose
transpose = [[0 for j in range(rows)] for i in range(cols)]
# Iterate over the elements of the original matrix and store them in the transpose
matrix
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
# Print the original matrix and the transpose matrix
print("Original Matrix:")
for row in matrix:
print(row)
print("Transpose Matrix:")
for row in transpose:
print(row)
[Link] a Python program to input a list of n numbers. Calculate and display the
average of numbers. Also display the cube of each value in the list.
n = int(input("Enter the number of elements in the list: "))
my_list = []
# Get the elements of the list from the user
for i in range(n):
num = int(input("Enter element {}: ".format(i+1)))
my_list.append(num)
# Calculate the average of the numbers in the list
average = sum(my_list) / n
print("The average of the numbers in the list is:", average)
# Calculate the cube of each value in the list and display it
print("The cube of each value in the list is:")
for num in my_list:
cube = num ** 3
print(cube)
[Link] a Python program to input a list of numbers. Calculate and display the
sum of cubes of each value in the list.
# Take input from the user
n = int(input("Enter the number of elements in the list: "))
my_list = []
# Get the elements of the list from the user
for i in range(n):
num = int(input("Enter element {}: ".format(i+1)))
my_list.append(num)
# Calculate the sum of cubes of each value in the list
sum_of_cubes = 0
for num in my_list:
cube = num ** 3
sum_of_cubes += cube
# Print the sum of cubes of each value in the list
print("The sum of cubes of each value in the list is:", sum_of_cubes)
16."Let student = {'John':50, 'Tom' :60, 'Nina':82} be a dictionary. Discuss the
output obtained after executing the following
statement.
newstudent = student
newstudent['Tom'] = 45
print newstudent
print student"
output
{'John': 50, 'Tom': 45, 'Nina': 82}.
[Link] in brief about List in python.
A list is a built-in data type in Python that represents an ordered collection of
elements. Lists are created using square brackets [] and can contain elements of
different data types, including numbers, strings, and other lists. Lists are mutable,
meaning that their elements can be changed after they are created
Lists are one of the most commonly used data structures in Python, and they are used
to store collections of related data. Lists can be used to store any type of data, and they
can be indexed and sliced to access individual elements or subsets of elements. Lists
can also be sorted, reversed, and concatenated using built-in functions
To create a list in Python, we can enclose a sequence of elements in square brackets,
separated by commas. For example, my_list = [1][2][3] creates a list with three
elements. We can also create an empty list using empty square brackets, like this:
my_list = []
Lists are commonly used to store collections of related data and can be indexed, sliced,
sorted, reversed, and concatenated using built-in functions.
In Python, we can iterate over a list using various methods. Here are some of the most
common ways to iterate over a list in Python:
Using a for loop: We can use a for loop to iterate over a list in Python. The loop
iterates over each element in the list and executes a block of code for each
element. For example:
my_list = [1, 2, 3, 4, 5]
for element in my_list:
print(element)
Using a for loop and range(): We can also use a for loop and the range()
function to iterate over a list. The range() function generates a sequence of
numbers that can be used as indices to access the elements of the list. For
example:
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
print(my_list[i])
Using a while loop: We can use a while loop to iterate over a list by using an
index variable to access the elements of the list. For example:
my_list = [1, 2, 3, 4, 5]
i=0
while i < len(my_list):
print(my_list[i])
i += 1
This code will also output the same result as the previous examples.
Using list comprehension: We can use list comprehension to iterate over a list
and perform some operation on each element. For example:
my_list = [1, 2, 3, 4, 5]
new_list = [element ** 2 for element in my_list]
print(new_list)
This code will output:
[1, 4, 9, 16, 25]
Using the enumerate() function: We can use the enumerate() function to iterate
over a list and access both the index and the element of each item. For example:
my_list = [1, 2, 3, 4, 5]
for i, element in enumerate(my_list):
print(i, element)
This code will output:
01
12
23
34
45
[Link] in brief about Tuple in python. Write operations with suitable examples
A tuple is a built-in data type in Python that represents an ordered collection of
elements. Tuples are created using parentheses () and can contain elements of different
data types, including numbers, strings, and other tuples. Tuples are immutable,
meaning that their elements cannot be changed after they are created.
To create a tuple in Python, we can enclose a sequence of elements in parentheses,
separated by commas. For example, my_tuple = (1, 2, 3) creates a tuple with three
elements. We can also create a tuple with a single element by including a trailing
comma, like this: my_tuple = (1,). We can access individual elements of a tuple using
indexing, like this: my_tuple.W e can perform various operations on tuples, including
concatenation, repetition, indexing, slicing, and getting the length.
Indexing: We can access individual elements of a tuple using indexing. For example:
my_tuple = (1, 2, 3)
print(my_tuple[0])
Slicing: We can access a subset of elements of a tuple using slicing. For example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])
This code will output:
(2, 3, 4)
Concatenation: We can concatenate two tuples using the + operator. For example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
new_tuple = tuple1 + tuple2
print(new_tuple)
This code will output:
(1, 2, 3, 4, 5, 6)
Repetition: We can repeat a tuple a certain number of times using the * operator. For example:
my_tuple = (1, 2, 3)
new_tuple = my_tuple * 3
print(new_tuple)
Length: We can get the length of a tuple using the len() function. For example:
my_tuple = (1, 2, 3)
print(len(my_tuple))
[Link] in brief about Set in [Link] operations with suitable examples.
A set in Python is an unordered collection of unique elements that are immutable,
meaning they cannot be changed once declared. Sets can be created using the built-in
set() function or by using curly braces {} syntax
Here are some examples of set operations in Python:
Adding elements to a set: Elements can be added to a set using the [Link]() function
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
Removing elements from a set: Elements can be removed from a set using the
[Link]() function.
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
Finding the length of a set: The number of elements in a set can be found using the
my_set = {1, 2, 3}
print(len(my_set)) # Output: 3
Union of sets: The union of two sets can be found using the | operator or the union()
method
For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
print([Link](set2)) # Output: {1, 2, 3, 4, 5}
Intersection of sets: The intersection of two sets can be found using the & operator or
the intersection() method
. For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2) # Output: {3}
print([Link](set2)) # Output: {3}
Difference of sets: The difference between two sets can be found using the - operator
or the difference() method
. For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 - set2) # Output: {1, 2}
print([Link](set2)) # Output: {1, 2}
Symmetric difference of sets: The symmetric difference between two sets can be
found using the ^ operator or the symmetric_difference() method
. For example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 ^ set2) # Output: {1, 2, 4, 5}
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}
[Link] in brief about Dictionary in [Link] operations with suitable
examples
A dictionary in Python is a collection of key-value pairs, where keys are unique and
values can be of any data type. Dictionaries are mutable, meaning they can be changed
after they are created
Here are some examples of dictionary operations in Python:
Creating a dictionary: Dictionaries can be created using curly braces or the built-in
dict() function
For example:
my_dict = {"key1": "value1", "key2": "value2"}
Accessing values: Values in a dictionary can be accessed using the [] operator
For example:
print(my_dict["key1"]) # Output: value1
Adding elements to a dictionary: Elements can be added to a dictionary using the []
operator or the setdefault() method
For example:
my_dict["key3"] = "value3"
print(my_dict) # Output: {"key1": "value1", "key2": "value2", "key3": "value3"}
Removing elements from a dictionary: Elements can be removed from a dictionary
using the pop() or del statement
For example:
my_dict.pop("key2")
print(my_dict) # Output: {"key1": "value1", "key3": "value3"}
Checking if a key exists: The in operator can be used to check if a key exists in a
dictionary
. For example:
if "key1" in my_dict:
print("Key exists")
else:
print("Key does not exist")
Length of a dictionary: The number of elements in a dictionary can be found using
the len() function
For example:
print(len(my_dict)) # Output: 3
Iterating through a dictionary: Dictionaries can be iterated using the keys(),
values(), and items() methods
For example:
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Copying a dictionary: The copy() method can be used to create a shallow copy of a
dictionary
. For example:
my_dict = {"key1": "value1", "key2": "value2"}
my_copy = my_dict.copy()
print(my_copy) # Output: {"key1": "value1", "key2": "value2"}
[Link] Indexing and Slicing operation for the list with example in python.
Indexing and slicing are two fundamental concepts in Python for accessing elements in
sequences, such as lists, tuples, and strings
Here are examples of indexing and slicing in Python:
Indexing:
Indexing is the process of accessing an element in a sequence using its position in the
sequence (its index)
The index starts from 0, and each element in the list has a unique index
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
print(my_list[1]) # Output: 2
print(my_list[4]) # Output: 5
Slicing:
Slicing is the process of accessing a sub-sequence of a sequence by specifying a
starting and ending index
The syntax for slicing is as follows: sequence[start_index:end_index]
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
print(my_list[:4]) # Output: [1, 2, 3, 4]
print(my_list[2:]) # Output: [3, 4, 5]
In the case of negative indexing, the index is calculated from the end of the list
python
my_list = [1, 2, 3, 4, 5]
print(my_list[-1]) # Output: 5
print(my_list[-2]) # Output: 4
print(my_list[-5]) # Output: 1
Slicing can also be used to modify a list by inserting or deleting elements
. For example:
python
my_list = [1, 2, 3, 4, 5]
my_list[1:4] = [10, 20, 30]
print(my_list) # Output: [1, 10, 20, 30, 4, 5]
Indices in Python are zero-based, meaning the first element in a list has an index of 0
[Link] append() and extend() are different with reference to list in Python?
The append() and extend() methods in Python are used to add elements to a list, but
they have different behaviors:
append(): This method adds a single element to the end of the list
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
extend(): This method concatenates the first list with another list or iterable,
effectively appending all the elements of the iterable to the end of the original list
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
append() adds a single element to the end of the list.
extend() adds all the elements of an iterable to the end of the list.
Using extend() can be more efficient than using append() in a loop, as it requires fewer
allocate operations
Additionally, extend() makes the code more readable, as it avoids the need for a loop
to add multiple elements
[Link] sorted() can be used with list in Python? Give an example.
The sorted() function in Python is used to sort an iterable, such as a list, tuple, or string
returns a new sorted list, leaving the original iterable unchanged
Here's an example of using sorted() to sort a list of numbers:
my_list = [5, 2, 3, 1, 4]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3, 4, 5]
The sorted() function can also be used to sort strings, treating each character as a
separate element
my_string = "python"
sorted_string = sorted(my_string)
print(sorted_string) # Output: ['h', 'o', 'p', 'y', 't']
The sort() method, on the other hand, is a list method that modifies the list in-place
and sorts the elements in ascending order
. It has two optional parameters: key and reverse. The key parameter allows you to
specify a function that takes a single argument and returns a key to use for sorting. The
reverse parameter, when set to True, sorts the list in descending order
Here's an example of using sort() to sort a list of numbers:
my_list = [5, 2, 3, 1, 4]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4, 5]
sorted() is a built-in function that returns a new sorted list from an iterable.
sort() is a list method that modifies the list in-place and sorts the elements in ascending
order.
[Link] is dictionary in Python? Explain any four built-in dictionary methods
with example.
[Link] is dictionary in Python? Explain with an example.
[Link] tuple mutable? Demonstrate any two methods of tuple.
Tuples are immutable sequences of elements in Python, which means that once
a tuple is created, its contents cannot be changed. This means that you cannot
add or remove items from a tuple, nor can you modify the contents of the tuple
However, a tuple can contain mutable objects such as lists, and the contents of
those mutable objects can be changed
Here are two methods of tuples in Python:
count(): This method returns the number of times a specified element appears
in the tuple
For example:
my_tuple = (1, 2, 3, 2, 4, 2)
count = my_tuple.count(2)
print(count) # Output: 3
index(): This method returns the index of the first occurrence of a specified
element in the tuple
For example:
my_tuple = (1, 2, 3, 2, 4, 2)
index = my_tuple.index(3)
print(index) # Output: 2
Tuples are immutable, which means that you cannot modify their contents once they
are created. However, you can create a new tuple by concatenating two or more tuples
using the + operator