Why are lists called mutable types ?
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.
What are immutable counterparts of lists ?
Answer
Tuples are immutable, meaning once a tuple is created, its elements cannot be changed, added, or removed, unlike lists which are mutable.
What are different ways of creating lists ?
Answer
The different ways of creating lists are:
- Using Square Brackets [].
- Using the
list()constructor. - Using list comprehensions.
- Appending Elements.
- Using the
extend()method. - Using slicing.
What values can we have in a list ? Do they all have to be the same type ?
Answer
In Python, a list can contain values of different types, including integers, floats, strings, and even other lists or objects. There is no requirement for all elements in a list to be of the same type.
How are individual elements of lists are accessed and changed ?
Answer
Individual elements of lists in Python can be accessed and changed using their index, which starts at 0 for the first element. We can use both positive indexing, which counts from the start, and negative indexing, which counts from the end. To access an element, use my_list[index], and to change an element, assign a new value with my_list[index] = new_value.
How do you create the following lists ?
(a) [4, 5, 6]
(b) [-2, 1, 3]
(c) [-9, -8, -7, -6, -5]
(d) [-9, -10, -11, -12]
(e) [0, 1, 2]
Answer
(a) a = list(range(4, 7))
(b) b = [-2, 1, 3]
(c) c = list(range(-9, -4))
(d) d = list(range(-9, -13, -1))
(e) e = list(range(3))
If a = [5, 4, 3, 2, 1, 0] evaluate the following expressions :
(a) a[0]
(b) a[-1]
(c) a[a[0]]
(d) a[a[-1]]
(e) a[a[a[a[2] + 1]]]
Answer
(a) a[0]
5
The expression a[0] returns the first element of the list.
(b) a[-1]
0
The expression a[-1] returns the last element of the list.
(c) a[a[0]]
0
The value of expression a[0] is 5, so a[5] accesses the element at index 5, which is 0.
(d) a[a[-1]]
5
The value of expression a[-1] is 0, so a[0] accesses the element at index 0, which is 5.
(e) a[a[a[a[2] + 1]]]
1
First, evaluate a[2], which is 3.
Then, calculate a[2] + 1, which is 4.
Next, evaluate a[4], which is 1.
Then, evaluate a[1], which is 4.
Finally, evaluate a[4], which is 1.
Can you change an element of a sequence ? What if the sequence is a string ? What if the sequence is a list ?
Answer
Changing an element of a sequence depends on the type of sequence:
If the sequence is a string: We cannot change an element because strings are immutable in Python. Once a string is created, its content cannot be modified.
If the sequence is a list: We can change an element because lists are mutable. We can modify, add, or remove elements in a list.
What does a + b amounts to if a and b are lists ?
Answer
If a and b are lists, then a + b amounts to concatenation of the two lists. The elements of list b are appended to the end of list a, resulting in a new list containing the elements of both.
For example,
a = [1, 2, 3]
b = [4, 5, 6]
result = a + b
print(result)[1, 2, 3, 4, 5, 6]
What does a * b amounts to if a and b are lists ?
Answer
When both a and b are lists, the expression a * b will result in an error because the multiplication (*) operator is not defined for two lists in Python.
What does a + b amounts to if a is a list and b = 5 ?
Answer
If a is a list and b is an integer (b = 5), the expression a + b will raise an Error. This is because the '+' operator requires both the operands as list-types.
Is a string the same as a list of characters ?
Answer
No, a string is not the same as a list of characters.
A string is an immutable sequence of characters, meaning it cannot be changed after it is created. Each character in the string can be accessed by its index, but individual elements cannot be modified.
A list of characters is mutable, meaning you can modify, add, or remove characters.
Which functions can you use to add elements to a list ?
Answer
The functions used to add elements to a list are as follows:
- append()
- extend()
- insert()
What is the difference 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. |
What is the difference between pop() and remove() methods of list ?
Answer
| pop() method | remove() method |
|---|---|
The pop() method removes and returns the element at a specified index (if no index is specified, it removes the last element). | The remove() method removes the first occurrence of a specified element from the list. |
| It raises an IndexError if the index is out of range. | It raises a ValueError if the element is not found. |
| For example: L = [1, 2, 3] L.pop(1) Output — 2 | For example: L = [1, 2, 3, 2] L.remove(2) print(L) Output — [1, 3, 2] |
What is the difference between append() and extend() methods of list ?
Answer
| append() | extend() |
|---|---|
The append() method adds a single item to the end of the list. The single element can be list, number, strings, dictionary etc. | The extend() method adds one list at the end of another list. |
The syntax of append() method is list.append(item). | The syntax of extend() method is list.extend(list1). |
| For example: lst1 = [10, 12, 14] lst1.append(16) print(lst1) Output — [10, 12, 14, 16] | For example: t1 = ['a', 'b', 'c'] t2 = ['d', 'e'] t1.extend(t2) print(t1) Output — ['a', 'b', 'c', 'd', 'e'] |
How does the sort() work ? Give example.
Answer
The sort() function sorts the elements of a list in place, meaning it arranges the list elements either in ascending order (by default) or in descending order if the reverse=True argument is provided.
For example,
L = [5, 2, 9, 1, 7]
L.sort()
print(L) # Output: [1, 2, 5, 7, 9]
L.sort(reverse=True)
print(L) # Output: [9, 7, 5, 2, 1]In the first case, L.sort() arranges the elements in ascending order, while in the second case, L.sort(reverse=True) sorts them in descending order.
What does list.clear() function do ?
Answer
The list.clear() function removes all elements from the list, leaving it empty. After calling this method, the list will have no items, i.e., its length will be zero.
List can contain values of these types:
- integers
- floats
- lists
- tuples
- all of these
Answer
all of these
Reason — A list in Python can contain elements of any data type, including integers, floats, lists, tuples.
Which of the following will create an empty list?
- L = [ ]
- L = list(0)
- L = list()
- L = List(empty)
Answer
L = [ ], L = list()
Reason —
L = [ ]creates an empty list using square brackets.L = list()creates an empty list using thelist()constructor.
Which of the following will return the last element of a list L with 5 elements?
- L[5]
- L[4]
- L[-1]
- L[6]
Answer
L[4], L[-1]
Reason — In a list with 5 elements, the index of the last element is 4 (since indexing starts from 0). So, L[4] returns the last element. Additionally, negative indexing allows accessing elements from the end of the list, where L[-1] also returns the last element. Therefore, both L[4] and L[-1] return the last element.
If L = [1, 2] then L * 2 will yield
- [1, 2] * 2
- [1, 2, 2]
- [1, 1, 2, 2]
- [1, 2, 1, 2]
Answer
[1, 2, 1, 2]
Reason — The * operator in Python, when used with a list and an integer, repeats the elements of the list the specified number of times. Therefore, L * 2 duplicates the list L = [1, 2] twice, resulting in [1, 2, 1, 2].
If L1 = [1, 3, 5] and L2 = [2, 4, 6] then L1 + L2 will yield
- [1, 2, 3, 4, 5, 6]
- [1, 3, 5, 2, 4, 6]
- [3, 7, 11]
- [1, 3, 5, [2, 4, 6]]
Answer
[1, 3, 5, 2, 4, 6]
Reason — The + operator concatenates two lists in Python. When L1 + L2 is evaluated, the elements of L2 are appended to the end of L1, resulting in [1, 3, 5, 2, 4, 6].
Given a list L= [10, 20, 30, 40, 50, 60, 70], what would L[1 : 4] return?
- [10, 20, 30, 40]
- [20, 30, 40, 50]
- [20, 30, 40]
- [30, 40, 50]
Answer
[20, 30, 40]
Reason — The slicing L[1:4] extracts elements starting from index 1 up to index 3. In the list L = [10, 20, 30, 40, 50, 60, 70], the element at index 1 is 20, at index 2 is 30, and at index 3 is 40. Hence, the output is [20, 30, 40].
Given a list L = [10, 20, 30, 40, 50, 60, 70], what would L[2 : -2] return?
- [10, 20, 30, 40]
- [20, 30, 40, 50]
- [20, 30, 40]
- [30, 40, 50]
Answer
[20, 30, 40]
Reason — The slicing L[2 : -2] starts at index 2, which corresponds to the element 30, and goes up to the element at index -3, which is 50. Therefore, the elements included are at indices 2, 3, and 4, resulting in the sublist [30, 40, 50].
Given a list L = [10, 20, 30, 40, 50, 60, 70], what would L[-4 : -1] return?
- [20, 30, 40]
- [30, 40, 50]
- [40, 50, 60]
- [50, 60, 70]
Answer
[40, 50, 60]
Reason — L[-4] refers to the fourth element from the end, which is 40, and L[-2] refers to the last element, which is 60. The slicing L[-4 : -1] includes elements starting from index -4 up to index -2. Therefore, it returns the elements [40, 50, 60].
Given a list L = [10, 20, 30, 40, 50, 60, 70], what would L[-3 : 99] return?
- [20, 30, 40]
- [30, 40, 50]
- [40, 50, 60]
- [50, 60, 70]
Answer
[50, 60, 70]
Reason — In Python, negative indexing allows us to access elements from the end of the list. Here, L[-3] refers to the third element from the end, which is 50. The slicing L[-3 : 99] starts at L[-3] (50) and continues to the end of the list since the stop index 99 exceeds the length of the list. Therefore, it returns the elements from index -3 to the end: [50, 60, 70].
To find the last element of list namely 'smiles' in Python, .......... will be used.
- smiles[0]
- smiles[-1]
- smiles[lpos]
- smiles[:-1]
Answer
smiles[-1]
Reason — In Python, negative indexing allows access to elements from the end of a list. Using smiles[-1] accesses the last element of the list named smiles.
Out of the following, what is correct syntax to copy one list into another?
- listA = listB[ ]
- listA = listB[:]
- listA = listB[ ]( )
- listA = list(listB)
Answer
listA = listB[:], listA = list(listB)
Reason —
listA = listB[:]creates a copy oflistBusing slicing. The[:]notation means "take all elements from the beginning to the end" oflistB.listA = list(listB)creates a new list by passinglistBas an argument to thelist()constructor, which also results in a copy of the original list.
What is printed by the Python code?
print(list(range(3)))
- [0, 1, 2, 3]
- [1, 2, 3]
- [0, 1, 2]
- 0, 1, 2
Answer
[0, 1, 2]
Reason — The range(3) function generates a sequence of numbers starting from 0 up to 2. When this sequence is converted to a list using list() constructor, it results in the list [0, 1, 2].
Which of the following commands will create a list?
- list1 = list( )
- list1 = [ ]
- list1 = list([1, 2, 3])
- all of these
Answer
all of these
Reason — All these commands create lists in Python.
list1 = list()creates an empty list using thelist()constructor.list1 = []creates an empty list using the square brackets.list1 = list([1, 2, 3])creates a list containing the elements 1, 2, and 3 using thelist()constructor.
What is the output when we execute list("hello")?
- ['h', 'e', 'l', 'l', 'o']
- ['hello']
- ['llo']
- ['olleh']
Answer
['h', 'e', 'l', 'l', 'o']
Reason — The list() function converts the string "hello" into a list of its individual characters. Each character in the string becomes an element in the resulting list, resulting in ['h', 'e', 'l', 'l', 'o'].
What gets printed?
names = ['Hasan', 'Balwant', 'Sean', 'Dia']
print(names[-1][-1])- H
- n
- Hasan
- Dia
- a
Answer
a
Reason — The output of the print(names[-1][-1]) statement is a because names[-1] retrieves the last element of the list names, which is 'Dia'. The second [-1] accesses the last character of the string 'Dia', and since the last character is 'a', the output printed is 'a'.
What is the output of the following
l = [None] * 10
print(len(l))- 10
- 0
- Syntax Error
- None
Answer
10
Reason — The code initializes a list l with 10 elements, all set to None, using the expression [None] * 10. The len() function calculates the number of elements in the list, which is 10, and thus print(len(l)) outputs 10.
Consider the list aList - ["SIPO", [1, 3, 5, 7] ]. What would the following code print?
print(aList[0][1], aList[1][1])- S, 3
- S, 1
- I, 3
- I, 1
Answer
I, 3
Reason — In the given code,
- Expression:
aList[0][1]
aList[0]refers to the first element ofaList, which is the string "SIPO". The notation[1]accesses the character at index 1 of the string. In Python, string indexing starts from 0. Therefore:aList[0][0]is 'S' (the first character)aList[0][1]is 'I' (the second character)
So,
aList[0][1]evaluates to 'I'.
- Expression:
aList[1][1]
aList[1]refers to the second element ofaList, which is the list [1, 3, 5, 7]. The notation[1]accesses the element at index 1 of this list. Again, indexing starts from 0. Therefore:aList[1][0]is 1 (the first element)aList[1][1]is 3 (the second element)
Thus,
aList[1][1]evaluates to 3.
The print statement print(aList[0][1], aList[1][1]) outputs I 3, displaying both accessed values.
Which of the following is a standard Python library function and not an exclusively list function?
- append()
- remove()
- pop()
- len()
Answer
len()
Reason — The function len() is a standard Python library function that returns the number of items in an object, such as a list, string, or dictionary. In contrast, the functions append(), remove(), and pop() are list methods that manipulate lists.
Which of the following can add only one value to a list?
- add()
- append()
- extend()
- none of these
Answer
append()
Reason — The function append() can add only one value to a list at a time. When called, it takes a single argument and adds it to the end of the list.
Which of the following can add a list of elements to a list?
- add()
- append()
- extend()
- none of these
Answer
extend()
Reason — The function extend() can add a list of elements to an existing list. It takes an iterable (such as a list) as an argument and appends each element of that iterable to the end of the list.
Which of the following will always return a list?
- max()
- min()
- sort()
- sorted()
Answer
sorted()
Reason — The function sorted() will always return a list, regardless of the type of iterable passed to it (such as a list, tuple, or string). It creates a new sorted list from the elements of any iterable. In contrast, the sort() is a method that sorts a list in place and does not return a new list.
Which of the following can delete an element from a list if the index of the element is given?
- pop()
- remove()
- del
- all of these
Answer
pop(), del
Reason — The functions pop() and del can delete an element from a list if the index of the element is provided.
pop(index)removes and returns the element at the specified index from the list. If no index is given, it removes and returns the last item.del list[index]removes the item at the specified index without returning it.
On the other hand, remove(value) deletes the first occurrence of a specified value from the list.
Which of the following can delete an element from a list, if its value is given?
- pop()
- remove()
- del
- all of these
Answer
remove()
Reason — The remove() method deletes the first occurrence of a specified value from a list. In contrast, pop() and del can delete an element from a list if the index of the element is provided.
Which of the following searches for an element in a list and returns its index?
- search()
- find()
- index()
- lsearch()
Answer
index()
Reason — The index() function returns the index of first matched item from the list.
Which of the following can copy a list to another list?
- list()
- new()
- copy()
- = operator
Answer
list(), copy()
Reason — The list() function creates a new list that is a copy of an existing list, while the copy() method creates a copy of a list.
Lists are mutable data types and thus their values can be changed.
To create an empty list, function list() can used.
The + operator adds one list to the end another list.
The * operator replicates a list.
To check if an element is in list, in operator is used.
To delete a list slice from a list, del statement is used
A nested list contains another list as its member.
The insert() function is used to insert element at a designated position in a list.
The pop() function is used to delete element to remove an element from designated index in a list.
The extend() function can append a list elements to a list.
The sort() function sorts a list and makes changes in the list.
The sorted() function sorts a list and returns another list.
The list() and copy() are the similar functions.
Answer
False
Reason — Although list() and copy() are used for copying a list but these are two different functions while copy() creates a copy of a list, the list() type casts into list type.
The pop() and remove() are similar functions.
Answer
False
Reason — The pop() function removes an element from a specified position in the list and returns it. If no index is specified, pop() removes and returns the last item in the list. In contrast, the remove() function removes the first occurrence of a given item from the list. It will raise an error if the item is not found in the list.
A = [] and A = list() will produce the same result.
Answer
True
Reason — Both A = [] and A = list() create an empty list in Python. The first method uses square brackets, while the second method calls the built-in list() constructor. Both methods yield the same result: an empty list.
Lists once created cannot be changed.
Answer
False
Reason — Python lists are mutable, meaning we can change the elements of a list in place. Python does not create a new list when we modify an element. We can modify a list by adding, removing, or changing elements.
To sort a list, sort() and sorted(), both can be used.
Answer
True
Reason — Both sort() and sorted() can be used to sort a list in Python. The sort() method sorts the list in place and does not return anything, while sorted() creates a new list containing a sorted version of the list passed to it as argument. It does not modify the list passed as a parameter.
The extend() adds a single element to a list.
Answer
False
Reason — The function extend() adds a list of elements to an existing list. It takes an iterable (such as a list) as an argument and appends each element of that iterable to the end of the list.
The append() can add an element in the middle of a list.
Answer
False
Reason — The append() method adds an item to the end of the list.
The insert() can add an element in the middle of a list.
Answer
True
Reason — The insert() method in Python inserts an element at a specified index in a list.
The del statement can only delete list slices and not single elements from a list.
Answer
False
Reason — The del statement can be used to remove an individual item from a list, or to remove all items identified by a slice.
The del statement can work similar to the pop() function.
Answer
True
Reason — The del statement can remove an item from a list by its index, similar to the pop() function.
Assertion. In Python, unlike other types, you can change elements of a list in place.
Reason. Lists are mutable sequences.
- 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.
- Both A and R are false or not fully true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Python lists are mutable sequences, meaning we can change the elements of a list in place. Python does not create a new list when we modify an element. We can modify a list by adding, removing, or changing elements.
Assertion. Any comma-separated group of values creates a list.
Reason. Only a group of comma-separated values or expressions enclosed in [], creates a list.
- 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.
- Both A and R are false or not fully true.
Answer
A is false but R is true.
Explanation
A comma-separated group of values does not create a list. Lists are formed by placing a comma-separated-list of expressions or values in square brackets, [].
Assertion. Lists and strings have similar type of indexing.
Reason. Both lists and strings have two-way indexing, forward indexing and backward 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.
- Both A and R are false or not fully true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Both lists and strings in Python use similar type of indexing. They support two-way indexing, allowing access to elements with positive (forward) indices such as 0, 1, 2, 3,... and negative (backward) indices such as -1, -2, -3, -4, ....
Assertion. Lists are similar to strings in a number of ways like indexing, slicing and accessing individual elements.
Reason. Lists, unlike strings, are mutable.
- 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.
- Both A and R are false or not fully true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
Lists are similar to strings in a number of ways like indexing, slicing, accessing individual elements, using len() function, supporting membership operators. Both also allow the use of concatenation (+) and replication (*) operators. However, the key difference is that lists are mutable (their elements can be changed), while strings are immutable (their elements cannot be changed after creation).
Assertion. The membership operators in and not in work in the same way on lists as they do, with strings.
Reason. Some operators work differently on strings and lists, such as + and *.
- 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.
- Both A and R are false or not fully true.
Answer
A is true but R is false.
Explanation
The membership operators in and not in work on lists just like they work for strings, checking if an element is present or absent. Similarly, the + operator concatenates lists, and the * operator repeats the list a specified number of times, functioning the same way as with strings.
Assertion. A list slice is an extracted part of a list.
Reason. A list slice is a list in itself.
- 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.
- Both A and R are false or not fully true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
A list slice are the sub part of a list extracted out, and the resulting slice is itself a list, containing the elements from the original list within the specified range.
Discuss the utility and significance of Lists in Python, briefly.
Answer
Python lists are containers that can store an ordered list of values of same or different data types together in a single variable. The fact that elements of a list need not be homogeneous makes them highly adaptable and powerful data structure in Python. Lists provide fast access to its elements using index numbers. Python lists are mutable which makes them memory efficient. They serve as the basic building blocks for programs that process large amounts of data.
What do you understand by mutability? What does "in place" memory updation mean?
Answer
Mutability means that the value of an object can be updated by directly changing the contents of the memory location where the object is stored. There is no need to create another copy of the object in a new memory location with the updated values. This updation of the existing memory location of the object is called as in place memory updation.
Start with the list [8, 9, 10]. Do the following using list functions:
- Set the second entry (index 1) to 17
- Add 4, 5 and 6 to the end of the list
- Remove the first entry from the list
- Sort the list
- Double the list
- Insert 25 at index 3
Answer
listA = [8, 9, 10]
- listA[1] = 17
- listA.extend([4, 5, 6])
- listA.pop(0)
- listA.sort()
- listA = listA * 2
- listA.insert(3, 25)
If a is [1, 2, 3]
- what is the difference (if any) between a * 3 and [a, a, a]?
- is a * 3 equivalent to a + a + a?
- what is the meaning of a[1:1] = 9?
- what's the difference between a[1:2] = 4 and a[1:1] = 4?
Answer
- a * 3 ⇒ [1, 2, 3, 1, 2, 3, 1, 2, 3]
[a, a, a] ⇒ [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
So, a * 3 repeats the elements of the list whereas [a, a, a] creates nested list. - Yes, both a * 3 and a + a + a will result in [1, 2, 3, 1, 2, 3, 1, 2, 3]
- a[1:1] = 9 will cause an error because when list is modified using slices, the value being assigned must be a sequence but 9 is an integer not a sequence.
- Both a[1:2] = 4 and a[1:1] = 4 will cause error because when list is modified using slices, the value being assigned must be a sequence but 4 is an integer not a sequence. Assuming the question was a[1:2] = [4] and a[1:1] = [4], a[1:2] = [4] will change element at index 1 to 4 as a[1:2] gives a slice with a[1] as its only element. Thus, a becomes [1, 4, 3]. Coming to a[1:1] = [4], a[1:1] returns an empty slice so 4 is inserted into the list at index 1. Thus, a becomes [1, 4, 2, 3].
What's a[1 : 1] if a is a list of at least two elements? And what if the list is shorter?
Answer
a[x:y] returns a slice of the sequence from index x to y - 1. So, a[1 : 1] will return an empty list irrespective of whether the list has two elements or less as a slice from index 1 to index 0 is an invalid range.
How are the statements lst = lst + 3 and lst += [3] different, where lst is a list? Explain.
Answer
The statement lst = lst + 3 will give error as + operator in Python requires that both its operands should be of the same type but here one operand is list and other is integer. The statement lst += [3] will add 3 at the end of the lst as += when used with lists requires the operand on the right side to be an iterable and it will add each element of the iterable to the end of the list.
How are the statements lst += "xy" and lst = lst + "xy" different, where lst is a list? Explain.
Answer
The statement lst = lst + "xy" will give error as + operator in Python requires that both its operands should be of the same type but here one operand is list and other is string. The statement lst += "xy" will add 'x' and 'y' at the end of the lst as += when used with lists requires the operand on the right side to be an iterable and it will add each element of the iterable to the end of the list.
What's the purpose of the del operator and pop method? Try deleting a slice.
Answer
The del statement is used to remove an individual element or elements identified by a slice. It can also be used to delete all elements of the list along with the list object. For example,
lst = [1, 2, 3, 4, 5, 6, 7, 8]
del lst[1] # delete element at index 1
del lst[2:5] # delete elements from index 2 to 4
del lst # delete complete list pop() method is used to remove a single element from the given position in the list and return it. If no index is specified, pop() removes and returns the last element in the list. For example,
lst = [1, 2, 3, 4, 5, 6, 7, 8]
# removes element at
# index 1 i.e. 2 from
# the list and stores
# in variable a
a = pop(1)
# removes the last element
# i.e. 8 from the list and
# stores in variable b
b = pop()What does each of the following expressions evaluate to? Suppose that L is the list
["These", ["are", "a", "few", "words"], "that", "we", "will", "use"].
- L[1][0::2]
- "a" in L[1][0]
- L[:1] + L[1]
- L[2::2]
- L[2][2] in L[1]
Answer
- ['are', 'few']
- True
- ['These', 'are', 'a', 'few', 'words']
- ['that', 'will']
- True
Explanation
- L[1] returns ["are", "a", "few", "words"]. L[1][0::2] returns a slice of ["are", "a", "few", "words"] starting at index 0 covering every alternate element till the end of the list. So, final output is ['are', 'few'].
- L[1][0] is "are". As "a" is present in "are" so output is True.
- L[:1] return L[0] i.e. ["These"]. L[1] returns ["are", "a", "few", "words"]. + operator adds the two in a single list to give the final output as ['These', 'are', 'a', 'few', 'words'].
- L[2::2] returns a slice of L starting at index 2 covering every alternate element till the end of the list. So, final output is ['that', 'will'].
- L[1] is ["are", "a", "few", "words"]. L[2][2] is "a". As "a" is present in L[1] so output is True.
What are list slices? What for can you use them?
Answer
List slice is an extracted part of the list containing the requested elements. The list slice is a list in itself. All list operations can be performed on a list slice. List slices are used to copy the required elements to a new list and to modify the required parts of the list. For example,
lst = [1, 2, 3, 4, 5]
lst2 = lst[1:4] #lst2 is [2, 3, 4]
#Using Slices for list modification
lst[0:2] = [10, 20] #lst becomes [10, 20, 3, 4, 5]Does the slice operator always produce a new list?
Answer
Slice operator copies only the requested elements of the original list into a new list.
Compare lists with strings. How are they similar and how are they different?
Answer
The similarity between Lists and Strings in Python is that both are sequences. The differences between them are that firstly, Lists are mutable but Strings are immutable. Secondly, elements of a list can be of different types whereas a String only contains characters that are all of String type.
What do you understand by true copy of a list? How is it different from shallow copy?
Answer
True copy of a list means that the elements of the original list are copied to new memory locations and the new list contains references to these new memory locations for each element of the list. Hence, in case of true copy changes made to the original list will not reflect in the copied list and vice versa.
Incase of shallow copy of a list, the elements of the original list are not copied to new memory locations. Both the new list and the original list refer to the same memory locations for the elements of the list. Hence, changes made to one of the list reflect in the other list as well.
An index out of bounds given with a list name causes error, but not with list slices. Why?
Answer
When we use an index, we are accessing a constituent element of the list. If the index is out of bounds there is no element to return from the given index hence Python throws list index out of range error whereas list slicing always returns a subsequence and empty subsequence is a valid sequence. Thus, when a list is sliced outside the bounds, it still can return empty subsequence and hence Python gives no errors and returns empty subsequence.
What is the difference between appending a list and extending a list?
Answer
| Appending a list | Extending a list |
|---|---|
| For appending to a list, append() function is used. | For extending a list, extend() function is used. |
| The append() function can add a single element to the end of a list. | The extend() function can add multiple elements from a list supplied to it as argument. |
| After append(), the length of the list will increase by 1 element only. | After extend() the length of the list will increase by the length of the list given as argument to extend() |
Do functions max( ), min( ), sum( ) work with all types of lists.
Answer
No, for max() and min() to work on a list, the list must contain all elements of same type (non-complex type) and for sum() to work, the list must contain the elements which can be added such as numbers.
What is the difference between sort( ) and sorted( )?
Answer
| sort( ) | sorted( ) |
|---|---|
| It modifies the list it is called on. That is, the sorted list is stored in the same list; a new list is not created. | It creates a new list containing a sorted version of the list passed to it as argument. It does not modify the list passed as a parameter. |
| It works on a list and modifies it. | It can take any iterable sequence type, such as a list or a tuple etc, and it always returns a sorted list irrespective of the type of sequence passed to it. |
| It does not return anything (no return value). It modifies the list in place. | It returns a newly created sorted list. It does not change the passed sequence. |
What is the difference between following two expressions, if lst is given as [1, 3, 5]
(i) lst * 3 and lst *= 3
(ii) lst + 3 and lst += [3]
Answer
(i)
lst * 3 will give [1, 3, 5, 1, 3, 5, 1, 3, 5] but the original lst will remains unchanged, it will be [1, 3, 5] only.
lst *= 3 will also give [1, 3, 5, 1, 3, 5, 1, 3, 5] only but it will assign this result back to lst so lst will be changed to [1, 3, 5, 1, 3, 5, 1, 3, 5].
(ii)
lst + 3 will cause an error as both operands of + operator should be of same type but here one operand is list and the other integer.
lst += [3] will add 3 to the end of lst so lst becomes [1, 3, 5, 3].
Given two lists:
L1 = ["this", 'is', 'a', 'List'], L2 = ["this", ["is", "another"], "List"]
Which of the following expressions will cause an error and why?
- L1 == L2
- L1.upper( )
- L1[3].upper( )
- L2.upper( )
- L2[1].upper( )
- L2[1][1].upper( )
Answer
- L1.upper( ) will cause an error as upper() method can be called with Strings not Lists.
- L2.upper( ) will cause an error as upper() method can be called with Strings not Lists.
- L2[1].upper( ) will cause an error as L2[1] is a list — [ "is", "another"] and upper() method cannot be called on Lists.
From the previous question, give output of expressions that do not result in error.
Answer
- L1 == L2 gives output as false because L1 is not equal to L2.
- L1[3].upper( ) gives output as 'LIST' because L1[3] is 'List' and upper() function converts it to uppercase.
- L2[1][1].upper( ) gives output as 'ANOTHER' because L2[1] ["is", "another"] and L2[1][1] is "another". upper() function converts it to uppercase.
Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88]
- Which list slice will return [12, 25.7, [2, 1, 0, 5]]?
- Which expression will return [2, 1, 0, 5]?
- Which list slice will return [[2, 1, 0, 5]]?
- Which list slice will return [4.5, 25.7, 88]?
Answer
- L1[2:5]
- L1[4]
- L1[4:5]
- L1[1::2]
Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88], which function can change the list to:
- [3, 4.5, 12, 25.7, 88]
- [3, 4.5, 12, 25.7]
- [ [2, 1, 0, 5], 88]
Answer
- L1.pop(4)
- del L1[4:6]
- del L1[:4]
What will the following code result in?
L1 = [1, 3, 5, 7, 9]
print (L1 == L1.reverse( ) )
print (L1)Answer
False
[9, 7, 5, 3, 1]
L1 is not equal to its reverse so L1 == L1.reverse( ) gives False but L1.reverse( ) reverses L1 in place so after that statement executes, L1 becomes [9, 7, 5, 3, 1].
Predict the output:
my_list= [ 'p', 'r', 'o', 'b', 'l' , 'e', 'm']
my_list[2:3] = []
print(my_list)
my_list[2:5] = []
print(my_list)Answer
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'r', 'm']
my_list[2:3] = [] removes element at index 2 of my_list so it becomes ['p', 'r', 'b', 'l', 'e', 'm']. my_list[2:5] removes elements at indexes 2, 3, and 4 so now my_list becomes ['p', 'r', 'm'].
Predict the output:
List1 = [13, 18, 11, 16, 13, 18, 13]
print(List1.index(18))
print(List1.count(18))
List1.append(List1.count(13))
print(List1)Answer
1
2
[13, 18, 11, 16, 13, 18, 13, 3]
List1.index(18) gives the first index of element 18 in List1 which in this case is 1. List1.count(18) returns how many times 18 appears in List1 which in this case is 2. List1.count(13) returns 3 as 13 appears 3 times in List1. List1.append(List1.count(13)) add this 3 to the end of List1 so it becomes [13, 18, 11, 16, 13, 18, 13, 3].
Predict the output:
Odd = [1,3,5]
print( (Odd +[2, 4, 6])[4] )
print( (Odd +[12, 14, 16])[4] - (Odd +[2, 4, 6])[4] )Answer
4
10
Odd + [2, 4, 6] will return [1, 3, 5, 2, 4, 6]. The element at index 4 of this list is 4 so the first output is 4. (Odd +[12, 14, 16])[4] is 14 and (Odd +[2, 4, 6])[4] is 4. 14 - 4 = 10 which is the second output.
Predict the output:
a, b, c = [1,2], [1, 2], [1, 2]
print(a == b)
print (a is b)Answer
True
False
As corresponding elements of list a and b are equal hence a == b returns True. a is b returns False as a and b are two different list objects referencing two different memory locations.
Predict the output of following two parts. Are the outputs same? Are the outputs different? Why?
(a)
L1, L2 = [2, 4] , [2, 4]
L3 = L2
L2[1] = 5
print(L3) (b)
L1, L2 = [2, 4] , [2, 4]
L3 = list(L2)
L2[1] = 5
print(L3)Answer
Output of part (a) is:
[2, 5]
Output of part (b) is:
[2, 4]
As we can see, outputs of the two parts are different. The reason is that in part (a), the statement L3 = L2 creates a shallow copy of L2 in L3 i.e. both the variables L2 and L3 point to the same list. Hence, when element at index 1 of L2 is changed to 5, that change is visible in L3 also. On the other hand in part (b), the statement L3 = list(L2) creates a true copy (also called deep copy) of L2 so L3 points to a different list in memory which has the same elements as L2. Now when element at index 1 of L2 is changed to 5, that change is not visible in L3.
Find the errors:
- L1 = [1, 11, 21, 31]
- L2 = L1 + 2
- L3 = L1 * 2
- Idx = L1.index(45)
Answer
- Line 2 — L2 = L1 + 2 will result in error as one element of + is a list and other is an integer. In Python, operands of + operator should be of same type.
- Line 4 — Idx = L1.index(45) will cause an error as 45 is not present in the list L1.
Find the errors:
L1 = [1, 11, 21, 31]
An = L1.remove(41)Answer
L1.remove(41) will cause an error as 41 is not present in L1.
Find the errors:
L1 = [1, 11, 21, 31]
An = L1.remove(31)
print(An + 2)Answer
An + 2 will cause an error because remove() function does not return the removed element so An will be None. Addition operator (+) does not allow any of its operands to be None hence, it will raise a TypeError.
Find the errors:
L1 = [3, 4, 5]
L2 = L1 * 3
print(L1 * 3.0)
print(L2)Answer
The line print(L1 * 3.0) causes an error as Python does not allow multiplying a list with a non-int number and 3.0 is of float type.
Find the errors:
L1 = [3, 3, 8, 1, 3, 0, '1', '0', '2', 'e', 'w', 'e', 'r']
print(L1[: :-1])
print(L1[-1:-2:-3])
print(L1[-1:-2:-3:-4])Answer
The line print(L1[-1:-2:-3:-4]) causes an error as its syntax is invalid. The correct syntax for slicing a list is L1[start:stop:step].
What will be the output of following code?
x = ['3', '2', '5']
y = ''
while x:
y = y + x[-1]
x = x[:len(x) - 1]
print(y)
print(x)
print(type(x), type(y))Answer
523
[]
<class 'list'> <class 'str'>
The loop while x will continue executing as long as the length of list x is greater than 0. y is initially an empty string. Inside the loop, we are adding the last element of x to y and after that we are removing the last element of x from x. So, at the end of the loop y becomes 523 and x becomes empty. Type of x and y are list and str respectively.
Complete the code to create a list of every integer between 0 and 100, inclusive, named nums1 using Python, sorted in increasing order.
Answer
nums1 = list(range(101))
Let nums2 and nums3 be two non-empty lists. Write a Python command that will append the last element of nums3 to the end of nums2.
Answer
nums2.append(nums3[-1])
Consider the following code and predict the result of the following statements.
bieber = ['om', 'nom', 'nom']
counts = [1, 2, 3]
nums = counts
nums.append(4)- counts is nums
- counts is add([1, 2], [3, 4])
Answer
- Output is True as both nums and counts refer to the same list.
- This will cause an error as add function is not defined in the above code.
What is the output of the following code?
numbers = list(range(0, 51, 4))
results = []
for number in numbers:
if not number % 3:
results.append(number)
print(results)Answer
[0, 12, 24, 36, 48]
list(range(0, 51, 4)) will create a list from 0 to 48 with a step of 4 so numbers will be [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48]. For loop will traverse the list one number at a time. if not number % 3 means if number % 3 is equal to 0 i.e. number is divisible by 3. The numbers divisible by 3 are added to the results list and after the loop results list is printed.
Following code prints the given list in ascending order. Modify the code so that the elements are printed in the reverse order of the result produced by the given code.
numbers = list(range(0, 51, 4))
i = 0
while i < len(numbers):
print(numbers[i] , end = " ")
i += 3
# gives output as : 0 12 24 36 48Answer
numbers = list(range(0, 51, 4))
i = len(numbers) - 1
while i >= 0:
print(numbers[i] , end = " ")
i -= 348 36 24 12 0
Write a program to increment the elements of a list with a number.
lst = eval(input("Enter a list: "))
print("Existing list is:", lst)
n = int(input("Enter a number: "))
for i in range(len(lst)):
lst[i] += n
print("List after increment:", lst)Enter a list: [1, 2, 3, 4, 5]
Existing list is: [1, 2, 3, 4, 5]
Enter a number: 10
List after increment: [11, 12, 13, 14, 15]
Write a program that reverses a list of integers (in place).
l = eval(input("Enter a list: "))
print("Original list:", l)
l.reverse()
print("Reversed list:", l)Enter a list: [1, 2, 3, 4, 5]
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
Write a program that inputs two lists and creates a third, that contains all elements of the first followed by all elements of the second.
l1 = eval(input("Enter first list: "))
l2 = eval(input("Enter second list: "))
l3 = l1 + l2
print("Joined List:", l3)Enter first list: [1, 2, 3, 4, 5]
Enter second list: [11, 12, 13, 14, 15]
Joined List: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
Ask the user to enter a list containing numbers between 1 and 12. Then replace all of the entries in the list that are greater than 10 with 10.
l = eval(input("Enter list having numbers between 1 & 12: "))
for i in range(len(l)):
if l[i] > 10:
l[i] = 10
print("List after removing numbers greater than 10:")
print(l)Enter list having numbers between 1 & 12: [1, 3, 15, 8, 20]
List after removing numbers greater than 10:
[1, 3, 10, 8, 10]
Ask the user to enter a list of strings. Create a new list that consists of those strings with their first characters removed.
l1 = eval(input("Enter a list of strings: "))
l2 = []
for i in range(len(l1)):
l2.append(l1[i][1:])
print("List after removing first characters:")
print(l2)Enter a list of strings: ["red", "green", "blue", "pink", "cyan"]
List after removing first characters:
['ed', 'reen', 'lue', 'ink', 'yan']
Write a program to check if a number is present in the list or not. If the number is present, print the position of the number. Print an appropriate message if the number is not present in the list.
l = eval(input("Enter list: "))
n = int(input("Enter number to search: "))
if n in l:
print(n, "found at index", l.index(n))
else :
print(n, "not found in list")Enter list: [1, 3, 15, 8, 20]
Enter number to search: 15
15 found at index 2
=====================================
Enter list: [1, 3, 15, 8, 20]
Enter number to search: 25
25 not found in list
Create the following lists using a for loop:
A list consisting of the integers 0 through 49.
l = []
for i in range(50):
l.append(i)
print("List with integers from 0 to 49:")
print(l)List with integers from 0 to 49:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
Create the following lists using a for loop:
A list containing the squares of the integers 1 through 50.
l = []
for i in range(1, 51):
l.append(i * i)
print("List with square of integers from 1 to 50:")
print(l)List with square of integers from 1 to 50:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500]
Create the following lists using a for loop:
The list ['a','bb','ccc','dddd', . . . ] that ends with 26 copies of the letter z.
l = []
for i in range(1, 27):
l.append(chr(i + 96) * i)
print("Created List:")
print(l)Created List:
['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss', 'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu',
'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz']
Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4,6,13].
print("Enter two lists of same size")
L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []
for i in range(len(L)):
N.append(L[i] + M[i])
print("List N:")
print(N)Enter two lists of same size
Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]
Write a program rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc., and the element in the last index moves to the first index.
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)Enter the list: [8, 10, 13, 25, 7, 11]
Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]
Write a program that reads the n to display nth term of Fibonacci series.
The Fibonacci sequence works as follows:
- element 0 has the value 0
- element 1 has the value 1
- every element after that has the value of the sum of the two preceding elements
The beginning of the sequence looks like:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The program prompts for element and prints out the value of that element of the Fibonacci sequence.
Thus:
- input 7, produces 13
- input 9, produces 34
Hints:
A Don't try to just type out the entire list. It gets big very fast. Element 25 is 75205. Element 100 is 354224848179261915075. So keep upper limit of n to 20.
n = int(input("Enter n: "))
if (n > 20):
print("n should be less than or equal to 20")
else :
a = 0
b = 1
c = a + b
for i in range(3, n + 1):
a = b
b = c
c = a + b
print(n, "term of Fibonacci series =", c)Enter n: 7
7 term of Fibonacci series = 13
=====================================
Enter n: 9
9 term of Fibonacci series = 34
=====================================
Enter n: 25
n should be less than or equal to 20
Write programs as per following specifications:
'''Print the length of the longest
string in the list of strings str_list.
Precondition : the list will contain
at least one element.'''
l = eval(input("Enter list of strings: "))
largeIdx = 0
largeLen = 0
for i in range(len(l)):
length = len(l[i])
if length > largeLen:
largeLen = length
largeIdx = i
print("Longest String:", l[largeIdx])Enter list of strings: ["apple", "orange", "pear", "strawberry", "kiwi"]
Longest String: strawberry
Write programs as per following specifications:
'''L is a list of numbers. Print a new list where each element is the corresponding element of list L summed with number num.'''
l1 = eval(input("Enter list of numbers: "))
num = int(input("Enter the number to sum with (num): "))
l2 = []
for i in l1:
l2.append(i + num)
print("New list:")
print(l2)Enter list of numbers: [10, 20, 30, 40, 50]
Enter the number to sum with (num): 15
New list:
[25, 35, 45, 55, 65]
Write a program to read two lists num and denum which contain the numerators and denominators of same fractions at the respective indexes. Then display the smallest fraction along with its index.
num = eval(input("Enter numerators list: "))
denum = eval(input("Enter denominators list: "))
small = num[0] / denum[0]
smallIdx = 0
for i in range(len(num)):
t = num[i] / denum[i]
if t < small:
small = t
smallIdx = i
print("Smallest Fraction =", num[smallIdx], "/", denum[smallIdx])
print("Index of Smallest Fraction =", smallIdx)Enter numerators list: [1, 3, 1, 7, 3]
Enter denominators list: [2, 4, 4, 13, 8]
Smallest Fraction = 1 / 4
Index of Smallest Fraction = 2
Write a program to display the maximum and minimum values from the specified range of indexes of list.
l = eval(input("Enter the list: "))
start = int(input("Enter start index: "))
stop = int(input("Enter stop index: "))
slice = l[start : stop + 1]
mx = max(slice)
mi = min(slice)
print("Maximum =", mx)
print("Minimum =", mi)Enter the list: [89, 42, 12, 56, 35, 2, 8, 7, 13, 69]
Enter start index: 3
Enter stop index: 8
Maximum = 56
Minimum = 2
Write a program to move all duplicate values in a list to the end of the list.
l = eval(input("Enter the list: "))
dedup = []
dup = []
for i in l:
if i in dedup:
dup.append(i)
else:
dedup.append(i)
l = dedup + dup
print("Modified List:")
print(l)Enter the list: [20, 15, 18, 15, 7, 18, 12, 13, 7]
Modified List:
[20, 15, 18, 7, 12, 13, 15, 18, 7]
Write a program to compare two equal sized lists and print the first index where they differ.
print("Enter two equal sized lists")
l1 = eval(input("Enter first list: "))
l2 = eval(input("Enter second list: "))
for i in range(len(l1)):
if l1[i] != l2[i]:
print("Lists differ at index", i)
break;
else:
print("Lists are equal")Enter two equal sized lists
Enter first list: [80, 60, 50, 40, 30]
Enter second list: [80, 60, 55, 42, 30]
Lists differ at index 2
=====================================
Enter two equal sized lists
Enter first list: [80, 60, 50, 40, 30]
Enter second list: [80, 60, 50, 40, 30]
Lists are equal