Categories
python

difference between list and tuple

In this post , let us learn about the difference between list and tuple.

What are Lists?

Lists are compound data types storing multiple independent values .

It can accommodate different datatypes like integer, string, float, etc., within a square bracket.

In the below example, we have different types of data getting created with the list.

# Creating lists with multiple datatypes 
a = [1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
What are Tuples ?

Tuples are also one of the sequence datatypes as like Lists.

Tuples can be created by storing the data within round bracket or without any brackets.

#Creating tuple with round bracket
b=(1,2,3,'a','b','c','apple','orange',10.89,(6,7,8))
#Creating tuple without any brackets
c=1,2,3,'a','b','c','apple','orange',10.89,(6,7,8)
What is the difference between list and tuple?

Lists are mutable whereas tuples are immutable.

We can change the lists but not the tuples.

program
# Creating  list a
a=[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
# Displaying the data
a
# Displaying the datatype
type(a)
Result
[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
list

We can append the list as shown below, But we cannot change the tuple.

This is the difference between the tuple and the list.

program
# Trying to append data to it
a.append('d')
a
RESULT
[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89, 'd']