List
The data type list is an ordered sequence which is mutable and made up of one or more elements. Unlike a string which consists of only characters, a list can have elements of different data types, such as integer, float, string, tuple or even another list. A list is very useful to group together elements of mixed data types. Elements of a list are enclosed in square brackets and are separated by comma. Let us take some examples of lists in Python programming. #list1 is the list of five numbers
>>> list1 = [10,20,30,40,50]
>>> print(list1) [10,20,30,40,50] #list2 is the list of vowels
>>> list2 = ['a', 'e', 'i', 'o', 'u']
>>> print(list2) ['a', 'e', 'i', 'o', 'u'] #list3 is the list of mixed data types
>>> list3 = [100, 23.5, 'Hello']
>>> print(list3) [100, 23.5, 'Hello'] #list4 is the list of lists called nested #list
>>> list4 =[['Physics',101], ['Chemistry',202], ['Maths',303]]
>>> print(list4) [['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
Accessing Elements in a List
The elements of list are accessed in the same way as characters are accessed in string. Like string indices, list indices also start from 0. Let us take some examples of accessing element of a list using its index. #initializes a list list1
>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
2
>>> list1[3] #return fourth element of list1
8 #return error as index is out of range
>>> list1[15] IndexError: list index out of range #an expression resulting in an integer index
>>> list1[1+4]
12
>>> list1[-1] #return first element from right
12 #length of the list list1 is assigned to n
>>> n = len(list1)
>>> print(n)
6 #return the last element of the list1
>>> list1[n-1]
12 #return the first element of list1
>>> list1[-n]
2
Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1 =['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
>>> list1[2:6] ['Blue', 'Cyan', 'Magenta', 'Yellow'] #list1 is truncated to the end of the list
>>> list1[2:20] #second index is out of range ['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black'] #First index > second index so it results in an empty list.
>>> list1[7:2] [] #return sublist from index 0 to 4
>>> list1[:5] #first index missing ['Red', 'Green', 'Blue', 'Cyan', 'Magenta'] #slicing with a given step size
>>> list1[0:6:2] ['Red', 'Blue', 'Magenta'] #negative indexes #elements at index -6,-5,-4,-3 are sliced