0 votes
in Python by
What are lists and tuples? What is the key difference between the two?

1 Answer

0 votes
by

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97).

But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:

my_tuple = ('sara', 6, 5, 0.97)

my_list = ['sara', 6, 5, 0.97]

print(my_tuple[0])     # output => 'sara'

print(my_list[0])     # output => 'sara'

my_tuple[0] = 'ansh'    # modifying tuple => throws an error

my_list[0] = 'ansh'    # modifying list => list modified

print(my_tuple[0])     # output => 'sara'

print(my_list[0])     # output => 'ansh'

Related questions

0 votes
asked Oct 28, 2022 in Python by SakshiSharma
0 votes
asked Oct 4, 2022 in Redis by sharadyadav1986
...