0 votes
in Python by
What is the difference between list and tuple in Python?

1 Answer

0 votes
by

Both List and Tuple in Python are collection of data items, with the difference of whether it's mutable or not. Mutable means it's changeable or simply, you can change its contents. Immutable is the opposite of mutable. An immutable data type means you can't change or modify its state or content after it has been created. The most notable example of an immutable data type is string, which you can't modify after its creation. For List, it's mutable. We can see from the example below: Firstly, we create a list x. x = [1,2,3] Since List is mutable, you can add, remove and modify item(s) in that list: x.append(4) => [1,2,3,4] x.remove(3) => [1,2,4] x[0] = 5 => [5,2,4] As contrary, a Tuple is an immutable type, meaning that you can't change or modify any of its elements after creation: y = (1,2,3) y.append(4) => Error y.remove(4) => Error y[0] = 5 => Error If you take a further look to tuple's methods, it has comparably lesser methods than what a List has because of its immutable nature. Another word, a Tuple is said to be read-only. The only thing you can do with Tuple is to obtain its value stored: y[0] => 1 List is useful if you need to modify your data stored in the future, whereas Tuple is particularly useful if you want your data stored unable to modify and make it read-only data.

Related questions

0 votes
asked Dec 12, 2019 in Python by rajeshsharma
0 votes
asked Dec 14, 2019 in Python by sheetalkhandelwal
...