List in Python is classified as a Sequence data type.
A list consists of elements of heterogeneous type.
Lists are indexed by a/an integer data type.
Elements of a list are enclosed in square[] brackets.
Lists are mutable, you can update or edit the list.
remove() method is used to delete elements from a list if index is not known.
pop() and del command methods are used to delete elements from a list if index is known.
The append() method adds a single item to the existing list at the end.
You can compare two lists by using comparison operators.
The replication(*) operator replicates a list.
The assignment(=) operator creates a reference of the original list that shares the same memory location.
The insert() function inserts item into the list at the specified index.
The sort() function arranges the elements of the list either in ascending or descending order.
Python lists are mutable.
Answer
True
Reason — Lists are called mutable data types in Python because they allow modifications to be made to their elements after the list is created.
Lists are depicted through curly brackets only.
Answer
False
Reason — Lists are depicted through square brackets.
A list can contain heterogeneous values.
Answer
True
Reason — A list can contain heterogeneous values, meaning it can store elements of different data types.
We can create an empty list by using list() function.
Answer
True
Reason — In Python, an empty list can be created by using the list()
function.
A list is stored in memory as integer.
Answer
False
Reason — A list is not stored in memory as a single integer. Instead, it is stored as a collection of references to the elements it contains.
The command [1,2,3,4,]<[9,1] will give the output as True.
Answer
True
Reason — In Python, [1, 2, 3, 4] < [9, 1] returns True because list comparison is done element-wise from left to right. The comparison stops and returns True upon finding the first pair where the element in the first list is less than the corresponding element in the second list. Here, 1 < 9 is True, hence the result.
List[a:b] will give the elements between a and b.
Answer
False
Reason — List[a:b] will give the elements between a
and b-1
.
The append() function is used to add a value in a list at any place.
Answer
False
Reason — The append()
function adds a single item to the end of the list.
index() function will return the index of first matched item from the list.
Answer
True
Reason — The index()
function in Python returns the index of first matched item from the list.
extend() function is used to add multiple list items in a list.
Answer
True
Reason — The extend()
method adds one list at the end of another list. In other words, all the items of a list are added at the end of an already created list.
Consider the following statement:
List = ['h', 'o', 'i']
The length of the above list is:
- 5
- 3
- 0
- None of these
Answer
3
Reason — The length of a list in Python is determined by the number of elements it contains. The list ['h', 'o', 'i'] has three elements: 'h', 'o', and 'i'. Therefore, the length of the list is 3.
The list L1 contains [3, 4, 5, 6, 6, 8, 0]. What will be the output of the following expression?
print(L1 [-1])
- 0
- 3
- 5
- 8
Answer
0
Reason — In Python, negative indexing allows to access list elements starting from the end. The index -1 refers to the last element in the list. For the list L1 = [3, 4, 5, 6, 6, 8, 0]
, the last element is 0. So the output of print(L1[-1]) is 0.
Which of the following statements is correct about list?
- List can contain values of mixed data types.
- List can contain duplicate values.
- A list with no elements is called an empty list.
- All of these
Answer
All of these
Reason — Lists in Python can contain values of mixed data types, such as integers, strings, and floats. They can also contain duplicate values, meaning the same value can appear more than once in the list. Additionally, a list with no elements is called an empty list, represented as [].
Which operator can be used with list?
- in
- not in
- Both 1 & 2
- Arithmetic Operators only
Answer
Both 1 & 2
Reason — The operators in
and not in
can both be used with lists in Python. The in
operator checks if an element is present in the list, while the not in
operator checks if an element is not present in the list.
Which of the following commands will create a list?
- List1=list ()
- List1= []
- List1=[1,2,3,"a"]
- All of these
Answer
All of these
Reason — All of the provided commands will create a list in Python:
List1=list()
initializes an empty list using the list constructor.List1=[]
directly initializes an empty list using square brackets.List1=[1, 2, 3, "a"]
initializes a list with mixed data types including integers and a string.
What is the use of append() function in list?
- It adds an item to the end of the list.
- It adds an item at the beginning of the list.
- It adds an item anywhere in the list.
- All of these
Answer
It adds an item to the end of the list.
Reason — The append()
function adds a single item to the end of the list. It does not create a new list, rather it modifies the original list.
Select the output of the following expression:
str1 = "pen"
print(list(str1))
- ['p', 'e', 'n' ]
- [pen]
- [p/e/n]
- { "pen" }
Answer
['p', 'e', 'n']
Reason — The list()
function in Python can be used to convert a string into a list of its individual characters. Therefore, when we execute list(str1)
where str1 = "pen"
, it will convert the string "pen" into a list containing its characters: ['p', 'e', 'n'].
The sequential accessing of each of the elements in a list is called:
- List Indexing
- List Traversal
- List Slicing
- List Accessing
Answer
List Traversal
Reason — The sequential accessing of each of the elements in a list is called list traversal.
Consider the following lists:
L1 = ["this", "is", "a", "list"]
L2 = ["this", "is", "another list"]
Which of the following statements will result in an error?
- L1 = L2
- L1.copy()
- L2.append(1, 2, 3)
- L2.pop()
Answer
L2.append(1,2,3)
Reason — The append()
method in list takes one argument and adds it as a single element to the end of the list. Using L2.append(1, 2, 3)
will result in an error because it provides multiple arguments. The correct statement would be L2.append([1, 2, 3])
to add the entire list [1, 2, 3] as a single element to L2
.
Consider the following code:
>>>A = [10, 20, 30, 40]
>>>B = A.copy()
>>>A[2] = 50
>>>B
Which of the following will be the elements of list A and B?
- A = [10, 20, 50, 40]
B = [10, 20, 30, 40] - A = [10, 20, 30, 40]
B = [10, 20, 50, 40] - A = [10, 20, 30, 40, 50]
B = [10, 20, 50, 40] - A = [10, 20, 40]
B = [10, 20, 50, 40]
Answer
A=[10, 20, 50, 40]
B=[10, 20, 30, 40]
Reason — The code initializes list A
with elements [10, 20, 30, 40]. It then creates a copy of list A
named list B
using the copy()
method. Subsequently, the third element of list A
is modified to 50 using A[2] = 50
. At this point, B
is still [10, 20, 30, 40], because it's a separate list from A
. The copy()
method does not modify the original list or the modifications made in the new list will not be reflected to the base list.
Consider the following lists:
A = [1,2]
B = [1,2]
What will be the output of the following?
print(A==B)
- True
- False
- Error
- No output
Answer
True
Reason — When comparing lists A
and B
using the "==" operator print(A == B)
, Python checks if both lists have the same elements in the same order. In this case, both lists A
and B
contain the elements [1, 2], so the comparison A == B
evaluates to True.
Which of the following functions will return the first occurrence of the specified element in a list?
- sort()
- value()
- index()
- Sorted()
Answer
index()
Reason — The index()
function in Python returns the index of first matched item from the list.
Given A = "[22, 4.88, "India", "T"]" the data type of A is
- List
- String
- Dictionary
- Tuple
Answer
String
Reason — In Python, A = "[22, 4.88, "India", "T"]"
represents a string because it is enclosed in double quotes (").
Find the output of the following code:
number = [1, 5, 7, 0, 4]
print(number[2:3])
- [5]
- [7]
- [7,0]
- None of these
Answer
[7]
Reason — The slice number[2:3]
extracts a subset of the list starting from index 2 (inclusive) up to, but not including, index 3. In this case, index 2 corresponds to the element 7 in the list number
. Therefore, number[2:3]
results in [7].
What will be the output of the following operation?
L1 = [1,2]
L2 = [3, 4]
(L1 + L2)*2
- [2, 4, 6, 8]
- [1, 2, 3, 4, 1, 2, 3, 4]
- [1, 3, 4, 4]
- [3, 4, 1, 2]
Answer
[1,2,3,4,1,2,3,4]
Reason — The code initializes two lists, L1
with elements [1, 2] and L2
with elements [3, 4]. It then concatenates these two lists using the + operator, resulting in [1, 2, 3, 4]. Next, it multiplies this concatenated list by 2 using the * operator, which repeats the elements of the list. Therefore, the final output of (L1 + L2) * 2
is [1, 2, 3, 4, 1, 2, 3, 4].
Assertion (A): List in Python is a collection of values of any type.
Reasoning (R): In lists, you can change the elements of a list in place.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
List in Python is a collection of values of any type such as strings, integers, floats, objects or even a list. Lists in Python are mutable, meaning we can change the elements of a list in place.
Consider the given two statements:
T1 = [3, 9, 0, 1, 7]
T2 = [5, 1, 0, 7, 5.5]
Assertion (A): Output of print(len(T1) == len(T2))
is True.
Reasoning (R): The len()
function returns the number of elements in the list. If two lists have same number of elements, then ==
operator will return True.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
The output of print(len(T1) == len(T2))
is True because both T1
and T2
have the same number of elements (5 elements each). The len()
function returns the length of the list, i.e., the number of elements in a list.
Assertion (A): List traversal in Python is done through slicing and using for loop also.
Reasoning (R): Traversal can be done only through forward indexing.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is true but R is false.
Explanation
List traversal in Python can be done using slicing and a for loop. Both methods allow to access and iterate over elements in a list. Traversal in Python lists can be done through both forward and backward indexing.
Assertion (A): In Python, list is an immutable collection of data.
Reasoning (R): Mutable means that any change or alteration in data is mentioned in the same place. The updated collection will use the same address for its storage.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is false but R is true.
Explanation
In Python, list is a mutable collection of data, i.e., values in the list can be modified. The term "mutable" means that the objects can be changed in place, and any modifications to the object will use the same memory address.
Assertion (A): The position of each element in the list is considered as its index.
Reasoning (R): Indexing in a list can be positive and negative; index is defined using [] brackets.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
In Python, an index is a number specifying the position of an element in a list. Indexing in a list can be positive and negative. Positive indexing starts from 0 for the first element, while negative indexing starts from -1 for the last element. Indexing is defined using square brackets ([]).
Assertion (A): sort() method sorts the objects of list in ascending order.
Reasoning (R): Defining sort() method with reverse=True as an argument sorts the list elements in descending order.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
The sort() function sorts the items of the list, by default in ascending/increasing order. If we want to sort the list in decreasing order, we need to write: sort(reverse = True)
.
Assertion (A): An empty list can be created using list() method.
Reasoning (R): The following snippet—
>>>L1 = list()
>>>print(L1)
will give the output as:
[]
This statement holds true.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
An empty list can be created using list()
method. The provided code:
>>>L1 = list()
>>>print(L1)
will give the output as: [], which represents an empty list.
Assertion (A): List is mutable data type.
Reasoning (R): In-place change is not possible in list elements.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
A is true but R is false.
Explanation
In Python, list is an mutable data type, i.e., values in the list can be modified. In-place changes are possible in list elements. We can modify, add, or remove elements in a list directly.
Assertion (A): List slices are the sub-part of a list extracted out.
Reasoning (R): In Python, Slice operator[:] is used to select a range of elements from a sequence.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
List slices are the sub-parts of a list extracted out. In Python, Slice operator[:] is used to select a range of elements from a sequence. The syntax used for slicing is: list[start:stop:step]
.
What are the various ways to create a list?
Answer
The various ways of creating a list are :
- Using Square Brackets [].
- Using the list() constructor.
- Using list comprehensions.
- Appending Elements.
- Using the extend() method.
- Using slicing.
What are the similarities between strings and lists?
Answer
Both strings and lists are sequential data types, meaning they store elements in a specific order. They support indexing, allowing access to individual elements using square brackets notation '[]'. Additionally, both strings and lists support slicing, enabling us to extract portions of the sequence using the colon (:) operator. They can also be iterated over using loops such as for loops, facilitating access to each element one by one in the sequence. Furthermore, both strings and lists support the in and not in operators, which check for the presence or absence of a particular element in the sequence.
Why are lists called mutable data type?
Answer
Lists are called mutable data types in Python because they allow modifications to be made to their elements after the list is created. This mutability facilitates operations such as adding, removing, or modifying elements within the list even after its initial creation.
Define the following functions:
(a) len()
(b) append()
(c) extend()
(d) pop()
(e) remove()
(f) del
(g) sort()
(h) sorted()
(i) copy()
(j) count()
(k) max()
(I) min()
(m) sum()
Answer
(a) len() — The len()
function returns the length of the list, i.e., the number of elements in a list.
(b) append() — The append()
method adds a single item to the end of the list. It does not create a new list, rather it modifies the original list.
(c) extend() — The extend()
method adds one list at the end of another list. In other words, all the items of a list are added at the end of an already created list.
(d) pop() — The pop()
method removes the element from the specified index and also returns the element which was removed.
(e) remove() — The remove()
function removes the first occurrence of the item from the list. It is useful when we know the element to be deleted but not the index of the element.
(f) del — The del
statement removes the specified element from the list but does not return the deleted value.
(g) sort() — The sort()
function sorts the items of the list, by default in ascending/increasing order. To sort the list in descending order we use reverse = True
parameter. Sorting is done 'in place', i.e., it does not create a new list.
(h) sorted() — The sorted()
method takes a list as a parameter and creates a new list consisting of the same elements but arranged in ascending order and returns it as a list. To sort the list in descending order we use reverse = True
parameter.
(i) copy() — The copy()
function returns a new list stored in a different memory location.
(j) count() — The count()
method counts how many times an element has occurred in a list and returns it.
(k) max() — The max()
method returns the element with the maximum value from the list.
(I) min() — The min()
method returns the element with the minimum value from the list.
(m) sum() — The sum()
function in Python is used to calculate the sum of all the elements in list.
What is the difference between insert() and append() methods of a list?
Answer
Insert Method | Append Method |
---|---|
The insert() method is used to add an element at a specific index in the list. | The append() method is used to add an element at the end of the list. |
The syntax is: list.insert(index, element) . | The Syntax is: list.append(element) . |
Example: my_list.insert(2, 'hello') will insert the string 'hello' at index 2 in the list my_list. | Example: my_list.append('world') will add the string 'world' at the end of the list my_list. |
Suppose L = [10, ["few", "facts", "fun"], 3, 'Good']
Consider the above list and answer the following:
(a) L[3:]
(b) L[::2]
(c) L[1:2]
(d) L[1] [1]
Answer
(a) L[3:] — ['Good']
Explanation
The slice L[3:]
will include the element at index 3 and any elements that follow it. Since index 3 is the last element, L[3:] will include only ['Good'].
(b) L[::2] — [10, 3]
Explanation
The slice L[::2]
means to include every second element from the list, starting from the beginning. This results in selecting the elements at indices 0 and 2, which are 10 and 3.
(c) L[1:2] — [['few', 'facts', 'fun']]
Explanation
The slice L[1:2]
selects elements from index 1 up to, but not including, index 2. This means it includes only the element at index 1, which is ["few", "facts", "fun"].
(d) L[1] [1] — facts
Explanation
The expression L[1][1]
first accesses the sub-list at index 1, which is ["few", "facts", "fun"], and then accesses the element at index 1 of that sub-list, which is "facts". Therefore, L[1][1]
evaluates to "facts".
Find the output of the following:
L1=[1, 2, 3]
L2=[4, 5, 6]
print(L1+list ("45") )
print(L1.pop())
L1.remove (2)
print(L1)
L1.extend (L2)
print(L2)
Answer
[1, 2, 3, '4', '5']
3
[1]
[4, 5, 6]
In the above code, L1
is defined as [1, 2, 3] and L2
as [4, 5, 6]. The first print(L1 + list("45"))
concatenates L1
with the list representation of the string "45", resulting in [1, 2, 3, '4', '5']. The next operation print(L1.pop())
removes and returns the last element of L1
, which is 3, printing it. Then, L1.remove(2)
removes the element 2 from L1, leaving [1]. Subsequently, L1.extend(L2)
appends elements from L2
to L1
, modifying it to [1, 4, 5, 6]. Lastly, print(L2)
outputs [4, 5, 6], showing that L2
remains unchanged despite being extended into L1
.
What will be the output of the following statement?
list1 = [12, 32, 65, 26, 80, 10]
list1.sort()
print(list1)
[10, 12, 26, 32, 65, 80]
In the above code, list1
is initialized as [12, 32, 65, 26, 80, 10]. The sort()
method is then called on list1
, which arranges its elements in ascending order. After sorting, list1
becomes [10, 12, 26, 32, 65, 80].
What will be the output of the following statement?
list1 = [12, 32, 65, 26, 80, 10]
sorted(list1)
print(list1)
Answer
[12, 32, 65, 26, 80, 10]
In the given code, list1
is initialized as [12, 32, 65, 26, 80, 10]. The sorted(list1)
function is called, which creates and returns a new list with the elements of list1
sorted in ascending order, but it does not modify the original list1
. Since the sorted result is not stored or printed, the next line print(list1)
outputs the original unsorted list [12, 32, 65, 26, 80, 10].
What will be the output of the following statement?
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list1[::-2]
list1[:3] + list1[3:]
Answer
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In the given code, list1
is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The expression list1[::-2]
creates a new list with elements from list1
in reverse order, taking every second element, resulting in [10, 8, 6, 4, 2], but this new list is not stored or used further. The expression list1[:3] + list1[3:]
concatenates the first three elements [1, 2, 3] with the rest of the elements [4, 5, 6, 7, 8, 9, 10].
What will be the output of the following statement?
list1 = [1, 2, 3, 4, 5]
list1[len(list1)-1]
Answer
[1, 2, 3, 4, 5]
In the given code, list1
is initialized as [1, 2, 3, 4, 5]. The len(list1)
returns the number of elements in the list, which is 5. The len(list1) - 1
evaluates to 4 (i.e., 5 - 1). The list1[len(list1) - 1]
accesses the element at index 4, which is 5. However, since the result is not assigned to any variable or printed, it has no effect on the list.
What will be the output of the following code segment?
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(0, len(myList)):
if i % 2 == 0:
print (myList[i])
Answer
1
3
5
7
9
In the given code, myList
is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The for
loop iterates over the range of indices from 0 to len(myList)-1
. Inside the loop, the if
statement checks if the current index i
is even by using the modulus operator i % 2 == 0
. If the condition is true (i.e., the index is even), it prints the element at that index in myList
. As a result, the code prints all the elements at even indices, specifically: 1, 3, 5, 7, and 9.
What will be the output of the following code segment?
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[3:]
print(myList)
Answer
[1, 2, 3]
In the given code, myList
is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The del myList[3:]
statement deletes all elements in the list starting from index 3 to the end. This modifies myList
to only contain the elements from index 0 to 2. The subsequent print(myList)
statement then outputs the modified list [1, 2, 3].
What will be the output of the following code segment?
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[:5]
print(myList)
Answer
[6, 7, 8, 9, 10]
In the given code, myList
is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The del myList[:5]
statement deletes all elements in the list from the beginning up to, but not including, index 5. This removes the first five elements (1, 2, 3, 4, 5) from myList
. The subsequent print(myList)
statement then outputs the modified list, which is [6, 7, 8, 9, 10].
What will be the output of the following code segment?
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[::2]
print(myList)
Answer
[2, 4, 6, 8, 10]
In the given code, myList
is initialized as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The del myList[::2]
statement deletes elements in the list with a step of 2, starting from the beginning of the list. This means, it removes every second element from myList
. Specifically, it deletes elements at indices 0, 2, 4, 6, and 8, which correspond to the values 1, 3, 5, 7, and 9. The subsequent print(myList)
statement then outputs the modified list, which is [2, 4, 6, 8, 10].
Write the output of the following Python program code:
Str2 = list("Cam@123*")
for i in range(len(Str2)-1):
if i==5:
Str2[i] = Str2[i]*2
elif (Str2 [i].isupper()):
Str2 [i] = Str2 [i]*2
elif (Str2 [i].isdigit()):
Str2 [i] = 'D'
print(Str2)
Answer
['CC', 'a', 'm', '@', 'D', '22', 'D', '*']
In the given code, Str2
is initialized as a list of characters from the string "Cam@123*"
, resulting in ['C', 'a', 'm', '@', '1', '2', '3', '*']. The for
loop iterates over the indices of Str2
from 0 to len(Str2) - 1
. Within the loop, three conditions modify the elements of Str2
: if the index i
is 5, the character at Str2[i]
is multiplied by 2, if the character is uppercase, it is also multiplied by 2, if the character is a digit, it is replaced with 'D'. After the loop, Str2
becomes ['CC', 'a', 'm', '@', 'D', '22', 'D', '*'], which is printed as the final output.
Differentiate between append() and insert() methods of list.
Answer
Insert Method | Append Method |
---|---|
The insert() method is used to add an element at a specific index in the list. | The append() method is used to add an element at the end of the list. |
The syntax is: list.insert(index, element) . | The Syntax is: list.append(element) . |
Example: my_list.insert(2, 'hello') will insert the string 'hello' at index 2 in the list my_list. | Example: my_list.append('world') will add the string 'world' at the end of the list my_list. |
Write a program to read a list of n integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.
n = int(input("Enter number of elements in the list: "))
nums = []
print("Enter the elements of the list:")
for i in range(n):
n1 = int(input("Enter element: "))
nums.append(n1)
positive = []
negative = []
for num in nums:
if num < 0:
negative.append(num)
else:
positive.append(num)
print("Original List:", nums)
print("Positive Numbers:", positive)
print("Negative Numbers:", negative)
Enter number of elements in the list: 6
Enter the elements of the list:
Enter element: 1
Enter element: -4
Enter element: 0
Enter element: -3
Enter element: 5
Enter element: 9
Original List: [1, -4, 0, -3, 5, 9]
Positive Numbers: [1, 0, 5, 9]
Negative Numbers: [-4, -3]
Write a program to find the largest and the second largest elements in a given list of elements.
nums = eval(input("Enter the list: "))
first = nums[0]
second = nums[0]
for num in nums[2:]:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
print("Largest element:", first)
print("Second largest element:", second)
Enter the list: [2, 8, 10, 18, 15, 6]
Largest element: 18
Second largest element: 15
Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values, then take their average.
Hint: Use an inbuilt function to sort the list.
n = int(input("Enter number of elements in the list: "))
nums = []
print("Enter the elements of the list:")
for i in range(n):
n1 = int(input("Enter element: "))
nums.append(n1)
nums.sort()
n = len(nums)
if n % 2 == 0:
mid1 = nums[n // 2 - 1]
mid2 = nums[n // 2]
median = (mid1 + mid2) / 2
else:
median = nums[n // 2]
print("Median of the list is:", median)
Enter number of elements in the list: 6
Enter the elements of the list:
Enter element: 10
Enter element: 20
Enter element: 4
Enter element: 45
Enter element: 99
Enter element: 30
Median of the list is: 25.0
Enter number of elements in the list: 5
Enter the elements of the list:
Enter element: 3
Enter element: 7
Enter element: 9
Enter element: 5
Enter element: 11
Median of the list is: 7
Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.
nums = eval(input("Enter list: "))
unique_nums = []
for num in nums:
if num not in unique_nums:
unique_nums.append(num)
print("The list without duplicates is: ", unique_nums)
Enter list: [11, 34, 67, 8, 66, 11, 8, 5]
The list without duplicates is: [11, 34, 67, 8, 66, 5]
Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also, input the position at which it is to be inserted.
list1 = eval(input("Enter list: "))
new_element = int(input("Enter the element to be inserted: "))
position = int(input("Enter the position at which the element should be inserted: "))
list1.insert(position, new_element)
print("Updated list:", list1)
Enter list: [23, 6, 7, 8, 9]
Enter the element to be inserted: 15
Enter the position at which the element should be inserted: 3
Updated list: [23, 6, 7, 15, 8, 9]
Write a program to read elements of a list and do the following:
(a) The program should ask for the position of the element to be deleted from the list and delete the element at the desired position in the list.
(b) The program should ask for the value of the element to be deleted from the list and delete this value from the list.
nums = eval(input("Enter list: "))
# Option (a): Delete element by position
position = int(input("Enter the position of the element to delete: "))
if 0 <= position < len(nums):
del nums[position]
print("List after deletion by position:", nums)
else:
print("Error: Position out of bounds. Please enter a valid position.")
# Option (b): Delete element by value
value = int(input("Enter the value of the element to delete: "))
if value in nums:
nums.remove(value)
print("List after deletion by value:", nums)
else:
print("Element", value, "not found in the list.")
Enter list: [44, 55, 66, 77, 33, 22]
Enter the position of the element to delete: 3
List after deletion by position: [44, 55, 66, 33, 22]
Enter the value of the element to delete: 22
List after deletion by value: [44, 55, 66, 33]
Write a program that accepts elements of a list S and adds all the odd values and displays the sum.
S = eval(input("Enter list: "))
sum_odd = 0
for num in S:
if num % 2 != 0:
sum_odd += num
print("The sum of all odd values in the list is: ", sum_odd)
Enter list: [43, 23, 5, 6, 8, 10, 12]
The sum of all odd values in the list is: 71
Write a program to calculate mean of a given list of numbers.
numbers = eval(input("Enter a list: "))
if len(numbers) == 0:
print("List is empty, cannot calculate mean.")
else:
total = sum(numbers)
n = len(numbers)
mean = total / n
print("Mean of the numbers:", mean)
Enter a list: [10, 30, 25, 34, 45, 98]
Mean of the numbers: 40.333333333333336
WAP in Python to delete all duplicate elements in a list.
For example,
If list is: [5, 2, 4, -5, 12, 2, 7, 4]
After deleting duplicate elements, new list should be: [5, 2, 4, -5, 12, 7]
nums = eval(input("Enter a list: "))
unique_nums = []
for num in nums:
if num not in unique_nums:
unique_nums.append(num)
print("The list after deleting duplicate elements is: ", unique_nums)
Enter a list: [5, 2, 4, -5, 12, 2, 7, 4]
The list after deleting duplicate elements is: [5, 2, 4, -5, 12, 7]
Write a program to calculate the minimum elements of a given list of numbers.
l = eval(input("Enter a list: "))
m = min(l)
print("Minimum element in the list:", m)
Enter a list: [1, 4, 65, 34, 23]
Minimum element in the list: 1
Write a code to calculate and display total marks and percentage of a student from the given list storing marks of a student.
marks_list = eval(input("Enter list of marks: "))
total_marks = sum(marks_list)
total_subjects = len(marks_list)
maximum_marks_per_subject = 100
total_marks_possible = maximum_marks_per_subject * total_subjects
percentage = (total_marks / total_marks_possible) * 100
print("Total Marks:", total_marks)
print("Percentage:", percentage)
Enter list of marks: [85, 90, 78, 92, 88]
Total Marks: 433
Percentage: 86.6
WAP to multiply an element by 2 if it is odd index for a given list containing both numbers and strings.
mixed = eval(input("Enter the list: "))
for index in range(1, len(mixed), 2):
mixed[index] *= 2
print("Modified List:", mixed)
Enter the list: [1, 'apple','banana', 5, 'cherry', 7, 'date', 'cherry']
Modified List: [1, 'appleapple', 'banana', 10, 'cherry', 14, 'date', 'cherrycherry']
WAP to count the frequency of an element in a given list.
my_list = eval(input("Enter the list: "))
c = int(input("Enter the element whose frequency is to be checked: "))
frequency = my_list.count(c)
print("The frequency of", c, "in the list is: ", frequency)
Enter the list: [1, 2, 3, 4, 1, 2, 1, 3, 4, 5, 1]
Enter the element whose frequency is to be checked: 1
The frequency of 1 in the list is: 4
WAP to shift elements of a list so that first element moves to the second index and second index moves to the third index, etc., and last element shifts to the first position.
Suppose list is [10, 20, 30, 40]
After shifting it should look like: [40, 10, 20, 30]
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Enter the list: [10, 20, 30, 40]
Original List
[10, 20, 30, 40]
Rotated List
[40, 10, 20, 30]
An array Num contains the following elements:
3, 25, 13, 6, 35, 8, 14, 45
Write a function to swap the content with next value divisible by 5 so that the resultant array looks like:
25, 3, 13, 35, 6, 8, 45, 14
Num = [3, 25, 13, 6, 35, 8, 14, 45]
for i in range(len(Num) - 1):
if Num[i] % 5 != 0 and Num[i + 1] % 5 == 0:
Num[i], Num[i + 1] = Num[i + 1], Num[i]
print("Resultant List:", Num)
Resultant List: [25, 3, 13, 35, 6, 8, 45, 14]
The record of a student (Name, Roll No, Marks in five subjects and percentage of marks) is stored in the following list:
studRecord = ['Rinku', 'A-36', [56, 98, 99, 72, 69], 78.8]
Write Python statements to retrieve the following information from the list studRecord.
(a) Percentage of the student
(b) Marks in the fifth subject
(c) Maximum marks of the student
(d) Roll No. of the student
(e) Change the name of the student from 'Rinku' to 'Rajat'
Answer
(a)
percentage = studRecord[3]
78.8
(b)
marks = studRecord[2][4]
69
(c)
max_marks = max(studRecord[2])
99
(d)
roll_no = studRecord[1]
A-36
(e)
studRecord[0] = 'Rajat'
['Rajat', 'A-36', [56, 98, 99, 72, 69], 78.8]