List and Tuple are built-in container types defined in Python. Objects of both these types can store different other objects that are accessible by index. List as well as tuple is a sequence data type, just as string. List as well as tuple can store objects which need not be of same type.
List : A List is an ordered collection of items (which may be of same or different types) separated by comma and enclosed in square brackets.
In [1]: L1=[10,25.5,3+2j,"Hello"] L1 Out[1]: [10, 25.5, (3+2j), 'Hello']
In above list, each item is of different type. Further, each item is accessible by positional index starting from 0. Hence L1[2] will return 25.5
In [2]: L1[1] Out[2]: 25.5
Tuple: Tuple looks similar to list. The only difference is that comma separated items of same or different type are enclosed in parentheses. Individual items follow zero based index, as in list or string.
In [3]: T1=(10,25.5,3+2j,"Hello") T1 Out[3]: (10, 25.5, (3+2j), 'Hello') In [4]: T1[1] Out[4]: 25.5
The obvious difference is the use of square brackets [] in List and parentheses () in tuple as enclosures. However, the important difference is that List as a mutable object and Tuple is an immutable object.
If contents of an object can be modified in place, after it has been instantiated, is a mutable object. On the other hand, any operation on immutable object that tries to modify its contents is prohibited.
In above example, any item in the list L1 can be assigned with different value. Let us change value of item at index=2 from 3+2j to 1.22E-5
In [5]: L1[2]=1.22E-5 L1 Out[5]: [10, 25.5, 1.22e-05, 'Hello']
The built-in List class has different methods that allow various operations on List object (such as insertion, deletion, sorting etc)
However, any such operation is not possible with Tuple object. If we try to modify T1 by changing value of item at index=2 to 1.22E-5, TypeError exception is raised.
In [6]: T1[2]=1.22E-5 T1 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-18a8ef5d3740> in <module>() ----> 1 T1[2]=1.22E-5 2 T1 TypeError: 'tuple' object does not support item assignment
Following built-in functions can be used along with List as well as Tuple.
len() | Returns number of elements in list/tuple |
max() | If list/tuple contains numbers, largest number will be returned. If list/tuple contains strings, one that comes last in alphabetical order will be returned. |
min() | If list/tuple contains numbers, smallest number will be returned. If list/tuple contains strings, one that comes first in alphabetical order will be returned. |
sum() | Returns addition of all elements in list/tuple |
sorted() | sorts the elements in list/tuple |
In [7]: L1=[10,30,50,20,40] T1=(10,50,30,40,20) print (len(L1)) print (len(T1)) print ('max of L1', max(L1)) print ('max of T1', max(T1)) print ('min of L1', min(L1)) print ('min of T1', min(T1)) print ('sum of L1', sum(L1)) print ('sum of T1', sum(T1)) print ('L1 in sorted order', sorted(L1)) print ('T1 in sorted order', sorted(T1)) Out[7]: 5 5 max of L1 50 max of T1 50 min of L1 10 min of T1 10 sum of L1 150 sum of T1 150 L1 in sorted order [10, 20, 30, 40, 50] T1 in sorted order [10, 20, 30, 40, 50]
If items in list/tuple are strings, min() and max() functions returns string that comes first/last in alphabetical order. If list/tuple is made up of numeric and nonnumeric values, TypeError exception is raised as comparison of dissimilar objects is not possible.
In [8]: L2=['pen', 'book','computer', 'table', 'file'] T2=('pen', 'book','computer', 'table', 'file') print ('max of L2', max(L2)) print ('max of T2', max(T2)) print ('min of L2', min(L2)) print ('min of T2', min(T2)) max of L2 table max of T2 table min of L2 book min of T2 book Out [9]: L3=[100, "hundred", 0.001] print ('max of L3', max(L3)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-9ea5851a5ca9> in <module>() 1 L3=[100, "hundred", 0.001] ----> 2 print ('max of L3', max(L3)) TypeError: '>' not supported between instances of 'str' and 'int'
The built-in list class has following methods to perform various operations on list object. Following methods allow new items to be added to list.
append() | appends an object to end of list |
copy() | makes a shallow copy of list |
count() | return number of occurrences of value in list |
extend() | extends the list by appending elements from another list/tuple |
insert() | inserts object in the list before given index |
In [10]: L1=[10,30,50,20,40] L1.append(100) #appends new item print ("after append",L1) L1.insert(2,30) #inserts new value at index print ('after insert',L1) c=L1.count(30) print ('count of 30',c) L1.extend([11,22,33]) print ('after extend', L1) Out [10]: after append [10, 30, 50, 20, 40, 100] after insert [10, 30, 30, 50, 20, 40, 100] count of 30 2 after extend [10, 30, 30, 50, 20, 40, 100, 11, 22, 33]
Following methods are used to remove items from given list.
pop() | removes and returns item at given index . Raises IndexError if list is empty or index is out of range. |
remove() | removes first occurrence of value in the list. Raises ValueError if the value is not present. |
clear() | remove all items from the list |
In [11]: p=L1.pop() print ('item popped:', p) print ('list after popping', L1) L1.remove(100) print ('after removing value :',L1) L1.clear() print ('all cleared:', L1) Out [11]: item popped: 33 list after popping [10, 30, 30, 50, 20, 40, 100, 11, 22] after removing value : [10, 30, 30, 50, 20, 40, 11, 22] all cleared: []
Following methods rearrange sequence of items in the list
reverse() | reverses the list in place |
sort() | sorts the list in place |
In [12]: L1=[10, 30, 30, 50, 20, 40, 11, 22] print ('original list :', L1) L1.reverse() print ('after reversing:',L1) L1.sort() print ("sorted list: ", L1) Out [12]: original list : [10, 30, 30, 50, 20, 40, 11, 22] after reversing: [22, 11, 40, 20, 50, 30, 30, 10] sorted list: [10, 11, 20, 22, 30, 30, 40, 50]
If you recall, tuple is an immutable object. Hence the tuple class doesn’t have similar methods perform insertion, deletion or rearrangement of items.
All sequence type objects (string, list and tuple) are inter-convertible. Python’s built-in functions for this purpose are explained below:
list() | converts a tuple or string to list |
tuple() | converts list or string to tuple |
str() | returns string representation of list or tuple object |
In [13]: L1=[10, 30, 30, 50, 20, 40, 11, 22] T1=tuple(L1) print (T1) (10, 30, 30, 50, 20, 40, 11, 22) In [14]: T1=(10,50,30,40,20) L1=list(T1) print (L1) [10, 50, 30, 40, 20] In [15]: s1="Hello" L2=list(s1) print ('string to list:', L2) T2=tuple(s1) print ('string to tuple', T2) string to list: ['H', 'e', 'l', 'l', 'o'] string to tuple ('H', 'e', 'l', 'l', 'o') In [16]: s1=str(L1) s2=str(T1) print ('list to string',s1) print ('tuple to string',s2) list to string [10, 50, 30, 40, 20] tuple to string (10, 50, 30, 40, 20)
When a list or tuple is converted to string by str() function, the string representation is not exactly similar to word, but list or tuple surrounded by single quote marks. To form a continuous sequence of characters in the list, use join() method of string object.
In [17]: L2=['H', 'e', 'l', 'l', 'o'] s1=str(L2) s1 Out[17]: "['H', 'e', 'l', 'l', 'o']" In [18]: s2="".join(L2) print ('string from list items:', s2) string from list items: Hello
In this chapter, we discussed the list and tuple objects, their functions and methods. In next chapter we shall learn about dictionary data type.
This is my first time here. I am truly impressed to read all this in one place.
Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!
Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.
Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.
Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.
C# is an object-oriented programming developed by Microsoft that uses ...
Leave a Reply
Your email address will not be published. Required fields are marked *