Python errors with lists and tuples

I’m currently exploring the distinctions between lists and tuples in Python, but I’ve encountered some perplexing scenarios that have left me seeking clarification. Below is a code snippet that illustrates my areas of uncertainty:

# Code Snippet 1
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)

my_list[0] = 10
my_tuple[0] = 40

print(my_list, my_tuple)

Here are the specific errors I’m grappling with:

  1. Despite declaring my_list as a list, I encountered unexpected behavior when attempting to update its first element from 1 to 10. Can you explain why the value of my_list updates successfully, while attempting to update my_tuple results in an error indicating “TypeError: ‘tuple’ object does not support item assignment”?
  2. While attempting to update the first element of my_tuple from 4 to 40, I received an error indicating “TypeError: ‘tuple’ object does not support item assignment.” How can I modify the code to successfully update the value of my_tuple using a tuple assignment?
  3. After checking the console output, I found that the value of my_list is logged as [10, 2, 3], however the value of my_tuple remains unaltered at (4, 5, 6). What may be causing this disparity, and how can I verify that both data structures show the new values correctly?
  4. After reading this post, I’m not sure about the ramifications of utilizing lists vs tuples in Python, particularly in terms of mutability and immutability. Could you explain when to utilize lists and tuples depending on their respective properties?

Your ideas and advice would be highly welcomed as I work through these problems and improve my grasp of lists and tuples in Python. Thank you for the assistance.

As you’ve found tuples are immutable: you cannot change them

https://stackoverflow.com/questions/42034/what-is-a-tuple-useful-for

Tuples are used whenever you want to return multiple results from a function.
Since they’re immutable, they can be used as keys for a dictionary (lists can’t).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.