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. Show
Lists and Tuples are similar in most context but there are some differences which we are going to find in this article. Syntax DifferencesSyntax 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 Tuplelist_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() functiontype(list_num) type(tup_num)Output: list tupleMutable List vs Immutable TuplesList 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. Tuplelist_num[2] = 5 print(list_num) tup_num[2] = 5Output: [1,2,5,4] Traceback (most recent call last): File "python", line 6, in <module> TypeError: 'tuple' object does not support item assignmentIn 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 OperationsLists 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 Directorydir(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 Directorydir(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 ComparisonTuples 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. Tuplea= (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= 120In above code we have tuple a and list b with same items but the size of tuple is less than the list. Different Use CasesAt first sight, it might seem that lists can always replace tuples. But tuples are extremely useful data structures
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} #InvalidKey points to remember:
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. Related guide for Which Statement Is Correct List Is Mutable And Immutable?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: 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”. A double B float C integer D int AnswerD 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 AnswerD 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 AnswerC 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 AnswerB 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 AnswerC 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: 753429226. What is the data type of print[type[0xEE]]?A int B hex C hexint D number AnswerA We can display integers in binary, octal and hexadecimal formats.
A True B False AnswerB {} 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 AnswerC 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 AnswerC ‘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 AnswerB 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] AnswerD mylist[0] gives the first element while mylist[1] gives the second element. A tuple B array C dictionary D list AnswerD 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 AnswerC To store values as regards key and value we use dictionary. 14. Can we use tuple as dictionary key?A True B False AnswerA 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 AnswerB 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
|