A

Answers Mode@itiwamm

Ask questions, get answers, find information and share your experience with Answers Mode.

📍 Dhaka, Bangladesh🔗 www.answersmode.com/📅 Joined Feb 2016
Answered 9 months ago
0 votes

What is the difference between a list and a tuple in Python?

What is the difference between a list and a tuple in Python? In Python, lists and tuples are both used to store collections of items. However, they have key differences in how they behave, which affects their use in programs. ✅ 1. Mutability List: Mutable – items can be added, removed, or changed. Tuple: Immutable – once created, items cannot be changed. Example (list): fruits = ["apple", "banana", "orange"] fruits.append("mango") # ✅ Add new item fruits[0] = "grape" # ✅ Change item Example (tuple): colors = ("red", "green", "blue") # colors[0] = "yellow" # ❌ TypeError ✅ 2. Syntax List: Use square brackets [] Tuple: Use parentheses () my_list = [1, 2, 3] my_tuple = (1, 2, 3) ✅ 3. Performance Tuple is faster than list for iteration and access, because tuples are immutable and optimized internally. Use tuple when data does not need to change for better performance. ✅ 4. Methods List has many built-in methods: append(), remove(), pop(), sort(), reverse() Tuple has very few methods: count(), index() (because it cannot be modified) ✅ 5. Use cases List: Dynamic data that changes frequently Example: Shopping cart items Tuple: Fixed data that shouldn’t change Example: RGB color codes, coordinates (x, y, z) 🔑 Summary Table Feature List Tuple Mutability Mutable Immutable Syntax [] () Methods Many (append, etc.) Few (count, index) Performance Slower Faster Use Case Changeable data Fixed data ✅ Example of using both # List for dynamic data shopping_cart = ["apple", "banana"] shopping_cart.append("mango") # Tuple for fixed data rgb = (255, 0, 0) Takeaway: Use list when you need to modify your collection. Use tuple when the collection should stay constant and you want better performance.  

View full answer & question →