Which of the following data types is immutable in Python?

126    Asked by DavidEdmunds in Python , Asked on Jul 15, 2024

Which of the following data guys is immutable in the context of Python programming language? Here are the options given below:-

  1. Lists

My_list = [1, 2, 3]

My_list.append(4)  # my_list is now [1, 2, 3, 4]

  1. Dictionaries

My_dict = {‘a’: 1, ‘b’: 2}

My_dict[‘c’] = 3  # my_dict is now {‘a’: 1, ‘b’: 2, ‘c’: 3}

  1. Sets

My_set = {1, 2, 3}

My_set.add(4)  # my_set is now {1, 2, 3, 4}

  1. Tuple

My_tuple = (1, 2, 3)

# Any attempt to modify my_tuple will result in an error

# For example: my_tuple[0] = 4 will raise a TypeError

Answered by Dipesh Bhardwaj

In the context of Python programming language, the option which is right regarding immutable data type in a python programming language is option 4 which refers to the tuple. A tuple is an ordered, immutable collection of elements in the Python programming language. Here are some key points given about the tuple:-

Creating a tuple

Tuples can be created by placing a sequence of values separated by the commas within the parentheses ():

My_tuple = (1, 2, 3)
Empty_tuple = ()

Singleton_tuple = (1,) # Note the comma

Accessing the elements

The elements in a tuple can be accessed by using indexing and slicing.

Print(my_tuple[0])  # Output: 1
Print(my_tuple[1:3]) # Output: (2, 3)

Immutability

Tuples cannot be changed or even modified after creation. If you ever try to modify, change, add, or remove an element, it would result in a Typerror.

My_tuple[0] = 4  # Raises TypeError
Packing and unpacking

Packing

Packed_tuple = 1, 2, 3
# packed_tuple is (1, 2, 3)

UnPacking

A, b, c = packed_tuple
# a is 1, b is 2, c is 3

Nesting tuples

The tuples can also contain other tuples as elements which would allow you to nest:

Nested_tuple = (1, (2, 3), 4)
# Access nested elementsPrint(nested_tuple[1][0])  # Output: 2Uses of Tuples

Fixed collection

When you need to ensure that the collection of items should not be changed or modified.

Function returns

It is very useful for returning multiple values from a particular function.

Dictionaries keys

The Tuples can be used as the keys in the dictionaries because they are immutable.

Example usage

Here is the example given below :

Def get_coordinates():
    Return (42.3601, -71.0589) # Latitude and Longitude of Boston
Coordinates = get_coordinates()


Your Answer

Interviews

Parent Categories