In Python, what is the difference between a list and a tuple?

Prepare for the TJR Bootcamp Test with quizzes and flashcards. Each question includes hints and explanations to boost your readiness for the exam!

Multiple Choice

In Python, what is the difference between a list and a tuple?

Explanation:
Mutability is the main idea here. A list in Python is mutable, meaning you can change its contents after it’s created. You can replace items by index, add items with append or extend, or remove items with pop or remove, all on the same object. A tuple, by contrast, is immutable: once it’s created, you can’t change its elements or its size. If you try to modify a tuple, Python raises a TypeError. If you need a different collection, you typically create a new tuple from parts, for example by concatenation, or convert to a list, modify it, then convert back. Because of this immutability, tuples can be used as dictionary keys or set elements (assuming their contents are hashable), whereas lists cannot be used in those roles. So the correct idea is that lists are mutable and tuples are immutable.

Mutability is the main idea here. A list in Python is mutable, meaning you can change its contents after it’s created. You can replace items by index, add items with append or extend, or remove items with pop or remove, all on the same object. A tuple, by contrast, is immutable: once it’s created, you can’t change its elements or its size. If you try to modify a tuple, Python raises a TypeError. If you need a different collection, you typically create a new tuple from parts, for example by concatenation, or convert to a list, modify it, then convert back.

Because of this immutability, tuples can be used as dictionary keys or set elements (assuming their contents are hashable), whereas lists cannot be used in those roles. So the correct idea is that lists are mutable and tuples are immutable.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy