<code>my_tuple = (<span class="hljs-string">'sara'</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>, <span class="hljs-number">0.97</span>) my_list = [<span class="hljs-string">'sara'</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>, <span class="hljs-number">0.97</span>] <span class="hljs-built_in">print</span>(my_tuple[<span class="hljs-number">0</span>]) <span class="hljs-comment"># output => 'sara'</span> <span class="hljs-built_in">print</span>(my_list[<span class="hljs-number">0</span>]) <span class="hljs-comment"># output => 'sara'</span> my_tuple[<span class="hljs-number">0</span>] = <span class="hljs-string">'ansh'</span> <span class="hljs-comment"># modifying tuple => throws an error</span> my_list[<span class="hljs-number">0</span>] = <span class="hljs-string">'ansh'</span> <span class="hljs-comment"># modifying list => list modified</span> <span class="hljs-built_in">print</span>(my_tuple[<span class="hljs-number">0</span>]) <span class="hljs-comment"># output => 'sara'</span> <span class="hljs-built_in">print</span>(my_list[<span class="hljs-number">0</span>]) <span class="hljs-comment"># output => 'ansh'</span></code>
Practice Problems
The primary difference between tuples and lists is that tuples are immutable as opposed to lists which are mutable. Therefore, it is possible to change a list but not a tuple. The contents of a tuple cannot change once they have been created in Python due to the immutability of tuples.
In short, lists and tuples are both sequence data types in Python. The key difference is that lists are mutable (modifiable), while tuples are immutable (unchangeable). Lists use square brackets [] for declaration and are suitable for situations where you need to add, remove, or modify elements. Tuples use parentheses () or no brackets for declaration and are used when you want to store a collection of values that should not be changed after creation.
