PCEP Data Structures 1 — Questions and Answers
Question 1: Which data structure in Python is mutable and ordered?
- tuple
- set
- list (Correct answer)
- dict
Correct answer: list
A Python list is an ordered collection of items, meaning elements maintain their insertion order and can be accessed by index. Crucially, lists are mutable, which means you can add, remove, or change elements after the list has been created. This makes them highly flexible for dynamic data storage and manipulation.
Question 2: Which of the following data structures is used to store unique elements in Python?
- list
- tuple
- set (Correct answer)
- dict
Correct answer: set
In Python, a `set` is an unordered collection of unique elements. This means that a set automatically prevents duplicate values from being stored, ensuring every element within it is distinct. Sets are highly efficient for operations like membership testing, removing duplicates from a sequence, and performing mathematical set operations.
Question 3: How do you create a tuple in Python?
- my_tuple = [1, 2, 3]
- my_tuple = (1, 2, 3) (Correct answer)
- my_tuple = {1, 2, 3}
- my_tuple = 1, 2, 3
Correct answer: my_tuple = (1, 2, 3)
Tuples in Python are created by enclosing a sequence of items in parentheses `()`, separated by commas. The syntax `my_tuple = (1, 2, 3)` explicitly defines `my_tuple` as an immutable sequence containing the integers 1, 2, and 3. While commas are the primary tuple constructor, parentheses are generally used for clarity and to avoid ambiguity.
Question 4: Which method would you use to remove an item from a list by its index in Python?
- remove()
- pop() (Correct answer)
- discard()
- delete()
Correct answer: pop()
The `pop()` method in Python lists is specifically designed to remove an item at a specified index. If no index is provided, `pop()` removes and returns the last item in the list. This method is particularly useful when you need to remove an element by its position and potentially use the removed value in subsequent operations.
Question 5: What is the difference between a list and a tuple in Python?
- Lists are immutable, while tuples are mutable.
- Tuples are immutable, while lists are mutable. (Correct answer)
- Lists and tuples are both mutable.
- Lists and tuples are both immutable.
Correct answer: Tuples are immutable, while lists are mutable.
The fundamental difference between lists and tuples in Python lies in their mutability. Tuples are immutable, meaning their elements cannot be changed, added, or removed after creation, making them suitable for fixed collections. Lists, conversely, are mutable, allowing their elements to be modified, added, or removed, providing flexibility for dynamic data.
Which data structure in Python is mutable and ordered?