Which statement is correct list is mutable and tuple is immutable

Lists and Tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be of any type including the nothing type defined by the None Keyword.

Lists and Tuples are similar in most context but there are some differences which we are going to find in this article.

Syntax Differences

Syntax of list and tuple is slightly different. Lists are surrounded by square brackets [] and Tuples are surrounded by parenthesis ().

Example 1.1: Creating List vs. Creating Tuple

list_num = [1,2,3,4] tup_num = (1,2,3,4) print(list_num) print(tup_num)

Output:

[1,2,3,4] (1,2,3,4)

Above, we defined a variable called list_num which hold a list of numbers from 1 to 4.The list is surrounded by brackets []. Also, we defined a variable tup_num; which contains a tuple of number from 1 to 4. The tuple is surrounded by parenthesis ().

In python we have type() function which gives the type of object created.

Example 1.2: Find type of data structure using type() function

type(list_num) type(tup_num)

Output:

list tuple

Mutable List vs Immutable Tuples

List has mutable nature i.e., list can be changed or modified after its creation according to needs whereas tuple has immutable nature i.e., tuple can’t be changed or modified after its creation.

Example 2.1: Modify an item List vs. Tuple

list_num[2] = 5 print(list_num) tup_num[2] = 5

Output:

[1,2,5,4] Traceback (most recent call last): File "python", line 6, in <module> TypeError: 'tuple' object does not support item assignment

In above code we assigned 5 to list_num at index 2 and we found 5 at index 2 in output. Also, we assigned 5 to tup_num at index 2 and we got type error. We can't modify the tuple due to its immutable nature.

Note: As the tuple is immutable these are fixed in size and list are variable in size.

Available Operations

Lists has more builtin function than that of tuple. We can use dir([object]) inbuilt function to get all the associated functions for list and tuple.

Example 3.1: List Directory

dir(list_num)

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Example 3.2: Tuple Directory

dir(tup_num)

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

We can clearly see that, there are so many additional functionalities associated with a list over a tuple.We can do insert and pop operation, removing and sorting elements in the list with inbuilt functions which is not available in Tuple.

Size Comparison

Tuples operation has smaller size than that of list, which makes it a bit faster but not that much to mention about until you have a huge number of elements.

Example 5.1: Calculate size of List vs. Tuple

a= (1,2,3,4,5,6,7,8,9,0) b= [1,2,3,4,5,6,7,8,9,0] print('a=',a.__sizeof__()) print('b=',b.__sizeof__())

Output:

a= 104 b= 120

In above code we have tuple a and list b with same items but the size of tuple is less than the list.

Different Use Cases

At first sight, it might seem that lists can always replace tuples. But tuples are extremely useful data structures

  1. Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed.
     
  2. Tuples are commonly used as the equivalent of a dictionary without keys to store data. For Example, [('Swordfish', 'Dominic Sena', 2001), ('Snowden', ' Oliver Stone', 2016), ('Taxi Driver', 'Martin Scorsese', 1976)] Above example contains tuples inside list which has a list of movies.
     
  3. Reading data is simpler when tuples are stored inside a list. For example, [(2,4), (5,7), (3,8), (5,9)] is easier to read than [[2,4], [5,7], [3,8], [5,9]]

Tuple can also be used as key in dictionary due to their hashable and immutable nature whereas Lists are not used as key in a dictionary because list can’t handle __hash__() and have mutable nature.

key_val= {('alpha','bravo'):123} #Valid key_val = {['alpha','bravo']:123} #Invalid

Key points to remember:

  1. The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets [] .
  2. Lists has variable length, tuple has fixed length.
  3. List has mutable nature, tuple has immutable nature.
  4. List has more functionality than the tuple.

Which statement is correct list is mutable and immutable? Explanation: List is mutable and Tuple is immutable. A mutable data type means that a python object of this type can be modified. An immutable object can’t. So, Option B is correct.

What are mutable objects in Python?

If immutable objects are objects whose value can’t change once created, a mutable object is an object whose value can change once created. Mutable objects are often objects that can store a collection of data. Lists (Python type list ) and dictionaries (Python type dict ) are examples of mutable objects.

Which statement is correct about lists and tuples in Python?

The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets [] . Lists has variable length, tuple has fixed length. List has mutable nature, tuple has immutable nature.

Which of the following is mutable data type?

9. Which one of the following is mutable data type? Explanation: set is one of the following is mutable data type.

Which of the following is not a mutable data type in Python?

The datatypes like int, float, bool, str, tuple, and Unicode are immutable. Datatypes like list, set, dict are mutable.

Which of the following statement is correct about list in Python?

Explanation: Elements of lists are stored in contagious memory location is the true regarding lists in Python.

Lists are mutable while tuples are immutable, and cannot be modified once created.

Tuples are hashable and can be used as dictionary keys, lists are not.

Tuples usually contain a heterogeneous sequence of elements that are accessed via unpacking, but not indexing.

Elements of lists are usually homogeneous and are accessed by iterating over the list.

Answer:
Tuples usually contain a heterogeneous sequence of elements that are accessed via unpacking, but not indexing.

Note: This Question is unanswered, help us to find answer for this one

December 26, 2020October 9, 2021 0 Comments

This collection of Python Multiple Choice Questions and Answers [MCQs]: Quizzes & Practice Tests with Answer focuses on “Data types”.

1. What is the data type of print[type[5]]?

A double

B float

C integer

D int

Answer

D

type[] function gives the class type of the argument. The output is : <class 'int'>

2. Which of the following is not a built-in data type?

A Dictionary

B Lists

C Tuples

D Class

Answer

D

Class is not a built-in data type, but a user defined data type.

3. Which of the following statement is correct?

A List and Tuple are Immutable

B List and Tuple are Mutable

C Tuple is immutable and List is mutable

D Tuple is mutable and List is immutable

Answer

C

Tuple is immutable and List is mutable. A mutable data type means that an object of this type can be modified. An immutable object can not be modified.

4. What is the output of the following code?str = "welcome" print[str[:2]]

A el

B we

C lc

D wel

Answer

B

We are displaying only the first two bytes of string, so the answer is “we”.

5. What is the return type of id[] function?

A bool

B list

C int

D double

Answer

C

id[] function returns an integer value that is unique. Example: Return the id of a tuple object:color = ['blue', 'green', 'red'] x = id[color]

Output:

75342922

6. What is the data type of print[type[0xEE]]?

A int

B hex

C hexint

D number

Answer

A

We can display integers in binary, octal and hexadecimal formats.

  • 0b or 0B for Binary
  • 0o or 0O for Octal
  • 0x or 0X for Hexadecimal

7. What is the output of the following code: print[type[{}] is set]?

A True

B False

Answer

B

{} show an empty dictionary while set[] is used to show an empty set.

8. In Python 3, what is the type of type[range[10]]?

A tuple

B int

C range

D list

Answer

C

range[] function gives a series of numbers, begining from 0, and increments by 1, and stops before a given number.

9. What type of error can arises when you execute the following code x = y?

A TypeError

B ValueError

C NameError

D SyntaxError

Answer

C

‘y’ is not defined so name error. The output:Traceback [most recent call last]: File "main.py", line 11, in <module> print[x = y] NameError: name 'y' is not defined

10. What is the output of the following code?def test[n]: n = n + '3' n = n * 3 return n print[test["hello"]]

A hello3hello3hello3

B IndentationError

C hello3

D None of the mentioned

Answer

B

Output: File "main.py", line 11 n = n * 3 ^ IndentationError: unexpected indent

11. Suppose we have a list with 6 elements. You can get the second element from the list using ________

A mylist[-2]

B mylist[2]

C mylist[-1]

D mylist[1]

Answer

D

mylist[0] gives the first element while mylist[1] gives the second element.

12. What is the data type of the following object?x = [5, 22, 'str', 1]

A tuple

B array

C dictionary

D list

Answer

D

List can store any values within it.

13. To store values as regards key and value we use ___________.

A tuple

B class

C dictionary

D list

Answer

C

To store values as regards key and value we use dictionary.

14. Can we use tuple as dictionary key?

A True

B False

Answer

A

A dictionary key have to be immutable. We can use a tuple as a key if the elements in the tuple are immutable.

15. What is the return value of trunc[] function?

A bool

B int

C float

D None

Answer

B

trunc[] function returns the truncated integer belong to a number. Example:print[math.trunc[2.77]] #Output: 2

MCQPractice competitive and technical Multiple Choice Questions and Answers [MCQs] with simple and logical explanations to prepare for tests and interviews. Spread the loveRead More

  • Python MCQ and Answers – Part 1
  • Python MCQ and Answers – Part 2
  • Python MCQ and Answers – Part 3
  • Python MCQ and Answers – Part 4
  • Python MCQ and Answers – Part 5
  • Python MCQ and Answers – Part 6
  • Python MCQ and Answers – Part 7
  • Python MCQ and Answers – Part 8
  • Python MCQ and Answers – Part 9
  • Python MCQ and Answers – Part 10
  • Python MCQ and Answers – Part 11
  • Python MCQ and Answers – Part 12
  • Python MCQ and Answers – Part 13
  • Python MCQ and Answers – Part 14
  • Python MCQ and Answers – Part 15
  • Python MCQ and Answers – Part 16
  • Python MCQ and Answers – Part 17
  • Python MCQ and Answers – Part 18
  • Python MCQ and Answers – Part 19
  • Python MCQ and Answers – Part 20
  • Python MCQ and Answers – Lists
  • Python MCQ and Answers – Strings
  • Python MCQ and Answers – Data types
  • Python MCQ and Answers – Variables And Operators – Part 2
  • Python MCQ and Answers – Variables And Operators – Part 1