Python Interview Questions
Question 1: How to create list and perform different operations on it?
Question 2: Can you add items of different data types in a list? What will be the output of following code snippet?
Answer: You can add items of different data types in a list. Below code shows items with different data types added in list and then printed.
Question 3: What happens if you try to delete an item from list using index that doesn’t exist in list?
Answer: It gives an error if you try to delete an item using invalid index.
Question 4: What happens if you add an element at an index where an elements already exists?
Answer: The element is inserted without an error and all existing elements get shifted one place.
In below example “xyz” is inserted at index 1 where “abc” already exists. Output shows elements at index 1 and 2 gets shifted.
Question 5: What happens if you try to sort list having mixed elements of type int and string?
Answer: Error is thrown if user tries to sort list having mixed types of int and string elements.
Question 6: What happens if you try to reverse list having mixed elements of type int and string?
Answer: list gets successfully reversed with mixed elements of type int and string.
Question 7: What are the different ways to convert a list of strings to a list of ints? for example – You are given a list something like [‘5′,’6′,’7′,’8′,’9’] and you need to convert this into [5,6,7,8,9].
Answer: There are different ways this can be accomplished.
Approach 1 – Iterate over the list and convert each element to int
Approach 2 – Using map function
Approach 3 – Using list composition