-
Classes
-
File operations
-
Comprehensions
-
loops
-
Python Installation
-
Numbers
-
Data Types in Python
-
Operators
-
Sequence Data types part 3 – Tuples
-
Sequence Data types part 2 – Lists
-
Expressions and statements
-
Data Unpacking
-
Functions
-
Dictionaries
-
Sequence Data types part 1-strings
-
if…else
-
Taking Input from the user
-
Python Typecasting
Lists
Lists are a type of data type which can store more than one value(collection of values) at a time. It is denoted by values enclosed within square brackets([ ]).
Output:
<class ‘list’>
Lists can store data of any type. It is not mandatory to store data collections of the same type. That means lists can be homogenous or heterogenous.
Lists support indexing which means we can access each element using numeric indices which start from 0.
For example,
Output:
1
23
4
5
76
Lists support the len() function
Output:
5
Iterating lists
Lists can be iterated using while loop when combined with the len() function
Output:
1
23
4
5
76
But Python has provided us with a better approach to loop through sequences. The approach is to use a for loop with a range() function.
Output:
1
23
4
5
76
But the for loop in Python can smartly detect a sequence data type and can directly access the elements of a sequence like a list as follows:
Output:
1
23
4
5
76
Accessing or modifying elements using index
We already know that elements of a list can be accessed using index values.
They also support negative indices. An index of -1 points to the last element of a list, -2 points to the second last element and so on.
But Python also allows modifying elements using the index values.
For example,
Here, the number at the first index is replaced with a new number that is 21. This way we can modify the elements of a given list. That’s why lists are said to be mutable which means they can be modified.
Lists also support slicing just like strings.
Output:
[1, 23]
[5]
[23, 4, 5]
[23, 4, 5]
This helps us to slice a list starting from the first specified index up to the second specified index but not including the second index just like strings.
If we omit the first value, it slices from the first index. And if we omit the last value, it slices up to the last index.
Output:
[1, 23, 4]
[5, 76]
Basic list methods
Let us now see some basic list methods which will help us to modify and manipulate lists
list.append()
Let’s say we have a list as follows:
numbers = [1,23,4,5,76]
If we want to add a new element to the list, we need to use the append() method as follows:
Output:
[1, 23, 4, 5, 76, 44]
Please note that the append() method always inserts an element to the end of the list. But if we want to insert elements at a particular index, we need to use the insert() method.
list.insert()
The insert method takes two arguments: first, the index at which we want to insert an element and second, the element that we want to insert.
Output:
[1, 23, 99, 4, 5, 76]
Here, the insert() method is inerting the value 99 at index 2 of the numbers list. Hence, upon printing, we get the updated list.
list.pop()
Next, if we want to remove an element from the end, we can use the pop() method as follows:
Output:
[1, 23, 4, 5]
But the pop() method can also help us to remove an element from a particular index. For that, we need to pass the index to the pop() method as follows:
Output:
[1, 23, 5, 76]
Here, the pop() method is accepting index 2 as argument and removing the value at index 2(the value 4) of the list.
list.remove(val)
Let us consider a different scenario where we want to remove a particular element from a given list without knowing the index. In this case, we have to use the remove() method as follows:
Output:
[1, 23, 4, 76]
Here, we are passing the value(not the index) to be removed to the remove() method. As the value 5 was passed, it removed the 5 from the list. If we pass a value which is not present in the list, we get a ValueError as follows:
Output:
ValueError: list.remove(x): x not in list
list.count()
The list.count() method will help us to count the number of occurrences of a particular value in a list. For example,
Interview Questions
Q. What is a list in Python, and how is it represented?
Ans. A list in Python is a versatile data structure that can store a collection of values. These values can be of different data types (homogeneous or heterogeneous). Lists are represented by enclosing the elements within square brackets [].
Q. How do you access elements within a list?
Ans. Elements within a list are accessed using indexing. Each element is associated with a numerical index starting from 0. For example, my_list[2] would access the third element in the list. Lists also support negative indexing, where my_list[-1] refers to the last element.
Q. Explain list mutability and how to modify elements.
Ans. Lists are mutable, meaning their contents can be modified after creation. Elements can be changed using their index: my_list[0] = 10 would replace the first element with the value 10.
Q. Describe two ways to iterate over a list in Python.
Ans. Using a for loop directly: It iterates over each element in the list automatically:
my_list = [23,12,45,76]
for item in my_list:
print(item)
Using a while loop and len(): This involves using a counter variable and the len() function to determine the list’s length.
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
Q. What is slicing in the context of lists, and how does it work?
Ans. Slicing is a way to extract a portion of a list. It’s done by specifying a start and end index within square brackets, separated by a colon [start:end]. The resulting slice includes elements from the start index up to, but not including, the end index. Omitting the start index starts from the beginning, and omitting the end index goes to the end of the list.
my_list = [1, 23, 4, 5, 76]
print(my_list[1:3]) # Output: [23, 4]
Q. What is the purpose of the len() function when working with lists?
Ans. The len() function returns the number of elements in a list. This is useful for iterating through a list using a while loop or determining the size of a list before performing other operations.
Q. When iterating over a list, what is the advantage of using a for loop over a while loop?
Ans. A for loop is generally preferred for list iteration because it’s more concise, easier to read, and less error-prone. It automatically handles the index and directly accesses each element, whereas a while loop requires manually managing a counter variable.
Q. If you wanted to retrieve a sublist containing the first three elements from a list, how would you achieve this using slicing?
Ans. You can use slicing to retrieve a sublist containing the first three elements. The syntax would be my_list[0:3]. This would return a new list containing the elements at index 0, 1, and 2.
Q. What happens if you try to access an element at an index that doesn’t exist within the list?
Ans. If you try to access an element at an index that is out of range (either negative and too large or positive and exceeding the list’s length), Python will raise an IndexError exception.
Q. Explain the difference between the following two slicing operations: my_list[1:4] and my_list[:4].
Ans.
- my_list[1:4] will return a new list containing the elements starting from index 1 (the second element) up to, but not including, index 4.
- my_list[:4] will return a new list containing the elements starting from the beginning of the list (index 0) up to, but not including, index 4. Effectively, this returns the first four elements of the list.
Q. How would you add a new element to the end of a list?
Ans. To add a new element to the end of a list, you can use the append() method. For example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Q. What’s the difference between the append() and insert() methods when working with lists?
Ans.
- append() adds a new element to the end of the list.
- insert() allows you to add a new element at a specific index within the list. It takes two arguments: the index and the element to insert.
Q. If you wanted to remove the last element from a list, which method would you use?
Ans. To remove the last element, you would use the pop() method without any arguments. This removes and returns the last element.
Q. Explain how to remove a specific element from a list by its value.
Ans. You can use the remove() method to remove the first occurrence of a specific value from a list. For example:
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
Q. How would you determine how many times a particular value appears in a list?
Ans. The count() method returns the number of times a specific value occurs in a list. For example:
my_list = [1, 2, 3, 2]
count_of_two = my_list.count(2)
print(count_of_two) # Output: 2
Code snippet based questions
Q. Analyze the following code snippet and explain the output:
numbers = [10, 20, 30, 40]
numbers[1] = 25
print(numbers[1])
Ans. The output of this code will be 25. The code first creates a list called numbers and then modifies the element at index 1 (the second element) to have the value 25. Finally, it prints the value at index 1, which is now 25.
my_list = [5, 10, 15, 20]
Q. What will this code snippet print?
print(my_list[-2:])
Ans. This will print [15, 20]. The slicing operation [-2:] means to start from the second to last element and go until the end of the list.
Q. Examine the following code and identify any potential errors:
fruits = [‘apple’, ‘banana’, ‘orange’]
fruits.remove(‘grape’)
Ans. This code will raise a ValueError because the remove() method tries to remove the value ‘grape’, which does not exist in the list.