InterviewSolution
| 1. |
List and tuple data types appear to be similar in nature. Explain typical use cases of list and tuple. |
|
Answer» Yes, the list and tuple objects are very similar in nature. Both are sequence data types being an ordered collection of ITEMS, not necessarily of the same type. However, there are a couple of subtle differences between the two. First and foremost, a tuple is an IMMUTABLE object while a list is mutable. Which simply means that once created, a tuple cannot be modified in place (insert/delete/update operations cannot be performed) and the list can be modified dynamically. Hence, if a collection is unlikely to be modified during the course of the program, a tuple should be used. For example price of items. >>> quantity=[34,56,45,90,60] >>> prices=(35.50, 299,50, 1.55, 25.00,99)Although both objects can contain items of different types, conventionally a list is used generally to hold similar objects – similar to an array in C/C++ or Java. Python tuple is preferred to set up a collection of heterogenous objects – similar to a STRUCT in C. CONSEQUENTLY, you would USE a list to store marks obtained by students, and a tuple to store coordinates of a point in cartesian system. >>> marks=[342,516,245,290,460] >>> x=(10,20)Internally too, Python uses tuple a lot for a number of purposes. For example, if a function returns more than one value, it is treated as a tuple. >>> def testfunction(): x=10 y=20 return x,y >>> t=testfunction() >>> t (10, 20) >>> type(t) <class 'tuple'>Similarly if a function is capable of receiving multiple arguments in the form of *args, it is parsed as a tuple. >>> def testfunction(*args): print (args) print (type(args)) >>> testfunction(1,2,3) (1, 2, 3) <class 'tuple'>Python uses tuple to store many built-in data structures. For example time data is stored as a tuple. >>> import time >>> time.localtime() time.struct_time(tm_year=2019, tm_mon=5, tm_mday=28, tm_hour=9, tm_min=20, tm_sec=0, tm_wday=1, tm_yday=148, tm_isdst=0)Because of its immutable nature, a tuple can be used as a key in a dictionary, whereas a list can’t be used as key. Also, if you want to iterate over a large collection of items, tuple proves to be faster than a list. |
|