[1, 2, 3] ['1', '2', '3'] ['123', 8] [7] [1, 2, False, [4, 5]]
5 Lists and Tuples
List is one of the most powerful data structures in Python. The List data type is made with so much of efforts and every programmer from beginner, intermediate to an expert should understand how it works.
Lists are mutable collection of objects. i.e. they are container to store a set of values of any data type.
for example:
Lists are ordered. We can index them and access values.
Lists are heterogeneous. A list can contain different types of elements.
Lists are mutable. You can change values in them.
5.1 Creating a Lists
5.1.1 Indexing and Slicing Lists
['milk', 14]
5.1.2 Modifying Lists
Unlike strings, lists are mutable. Its values can be changed.
['milk', 'Trucks', 9, 14, False]
5.2 Sorting List
The list.sort()
method sorts the elements of a list in ascending or descending order:
[1, 2, 3, 4, 5, 7]
[7, 5, 4, 3, 2, 1]
5.2.1 Sorting using a key parameters:
['Lahore', 'Karachi', 'Faisalabad', 'Hayderababd']
['Hayderababd', 'Faisalabad', 'Karachi', 'Lahore']
5.2.2 Removing Elements from the list
5.3 Converting a String to a List
String can be convert to a list, as per spaces ” ” or any other special characters “_”, according to the users choice, are encountered. To do this we use the split() method.
5.3.1 Syntax
string.split('delimiter')
['I', 'like', 'Python']
['I', 'Like', 'Python']
5.4 Tuples
Tuples are collections of Python objects. They are similar to lists but the difference between them is that tuples are immutable while lists are mutable. Tuples are created by typing a sequence of items, separated by commas. Optionally, you can put the comma-separated values in parenthesis.
Tuple1=(1,2,5,6)
Tuple2=(‘a’, “b”, ‘c’, “d”)
Tuple3 = () #empty tuple
Tuple4 = 5,3,1
Tuple5 = (“London”, “Tokyo”, “Korea”, 1986, 1640, 1948)
Note: To create a single item tuple, you have to use a comma after the value.
<class 'int'>
<class 'tuple'>
2
The values of tuples are stored at different index positions starting from zero. We can access the values by using their index positions inside square brackets. We can index or slice tuples like lists.
1
3
3
1
5.5 Tuple Unpacking
With a special syntax, Python can unpack the values of a tuple and extract them into single variables.
1
2
3
4
The number of variables to the left and right side should be the same and it assigns each variable respectively.
5.6 Lists Vs Tuples
5.6.1 Methods Available for List:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__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']
5.6.2 Methods Available for Tuple:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
As we observe that list have more methods as compare with tuples, but this extra functionality comes at a price i.e. list occupy more memoray than tuple. let’s have a look:
Help on built-in function getsizeof in module sys:
getsizeof(...)
getsizeof(object [, default]) -> int
Return the size of object in bytes.
None
The Size of the List is 120 bytes
The Size of the Tuple is 96 bytes
when working with big data, this can be significant.
List | Tuples |
---|---|
|
|
|
|
|
|
let’s have a look that how tuples are more efficient than lists:
time required to create 1000,000 lists and tuples of same size.
Time needed to make 1000000 lists:
0.034990400017704815
Time needed to make 1000000 tuples: 0.0072222000162582844
5.7 Exercise
Create a list
a_list
, with the following elements1
,hello
,[1,2,3]
andTrue
.Find the first and last value of the list.
Find the value stored at index 1 of
a_list
.Retrieve the elements stored at index 1, 2 and 3 of
a_list
.Concatenate the following lists
A = [1, 'a']
andB = [2, 1, 'd']
Make the list of the PIN of 5 officers and sort them in ascending and descending order.
Consider the following tuple and Find the length of the tuple,
genres_tuple
genres_tuple = (“pop”, “rock”, “soul”, “hard rock”, “soft rock”, “R&B”, “progressive rock”, “disco”)Access the element, with respect to index 3.
Use slicing to obtain indexes 3, 4 and 5.
Find the index of
"disco".
Generate a sorted List from the Tuple
C_tuple=(-5, 1, -3).
Check that a python tuple can’t be altered.
Find the sum of
list2 = [1,2,3,4]
.Write a program to count the number of occurrences of 4 in
tuple1=(4,1,2,5,7,4,8,4,4)
Reverse a list2 define above (Q.13) using index method.
Make the list of the words of “I am doing well”
sort the above created list as per length of the words in reverse order.
list1 =
[100, 200, 300, 400, 500]
, output =[500,400,300,200,100]
list2 =
[10, 20, [300, 400, [5000, 6000], 500], 30, 40]
, Expected output :[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
list1 =
["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
# sub list to addsub_list = ["h", "i", "j"]
Expected Output:["a", "b", ["c", ["d", "e", ["f", "g","h","i","j"], "k"], "l"], "m", "n"]
list1 =
[5, 10, 15, 20, 25, 50, 20]
Expected Output:[5, 10, 15, 200, 25, 50, 20]
list1 =
[5, 20, 15, 200, 25, 50, 220]
remove 20 from the list.