Python Lists, Tuples, Sets, and Dictionaries
Interview Questions
Comprehensive interview preparation guide covering core Python collections with examples.
1. Python Lists
Q: What is a list in Python?
A list is a mutable, ordered collection of items that can store elements of different data types.
Example: nums = [1, 2, 3].
Q: Difference between append() and extend()?
`append()` adds a single element, while `extend()` adds multiple elements. Example: [Link](4);
[Link]([5,6]).
Q: Explain list comprehension.
It provides a concise way to create lists. Example: squares = [x*x for x in range(5)].
2. Python Tuples
Q: What is a tuple?
A tuple is an immutable, ordered collection of elements. Example: t = (1, 2, 3).
Q: How do you convert a list into a tuple?
Use tuple(list_name). Example: tuple([1,2,3]) -> (1,2,3).
Q: Explain tuple unpacking.
You can assign tuple elements to variables directly. Example: a,b = (10,20).
3. Python Sets
Q: What is a set?
A set is an unordered collection of unique elements. Example: s = {1,2,3}.
Q: Explain union and intersection of sets.
Union: s1 | s2; Intersection: s1 & s2.
Q: What is a frozenset?
A frozenset is an immutable version of a set.
4. Python Dictionaries
Q: What is a dictionary?
A dictionary stores key-value pairs. Example: d = {'a':1, 'b':2}.
Q: Difference between get() and direct access?
`get()` returns None if the key is missing, avoiding KeyError.
Q: What is dictionary comprehension?
A concise way to create dicts. Example: squares = {x: x*x for x in range(5)}.
5. Scenario-Based Questions
Q: Convert a list of tuples into a dictionary.
Use dict(list_of_tuples). Example: dict([('a',1),('b',2)]).
Q: Find common elements between two lists.
Use set intersection: set(a) & set(b).
Q: Count frequency of elements.
Use [Link](list_name).