Lists, Tuples and Dictionary

The lists, tuples and Dictionary are Python's compound data types.A compound data type is one that holds multiple independent values.

Lists and Dictionary can be changed/ modified (i.e., mutable) but tuples cannot be changed or modified (i.e., immutable).
Values of type list are mutable i.e., changeable- one can change/ add/ delete a list's elements. But the values of type tuple are immutable i.e., non-changeable; one cannot make changes to a tuple .

List –

A List in Python represents a list of comma-separated values of any datatypes between square brackets e.g., following are some lists:
[1, 2, 3, 4, 5]
 [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
 [‘Rekha’, 104, 98.5]

Like any other value, you can assign a list to a variable e.g.,
>>>a   or  print(a)

The values stored in a list can be accessed using the slice operator ( [ ] and [:] ) with indexes starting at 0 in the beginning of the list and working their way to end -1.
To change first value in a list namely a, we may write-
>>> print(a)


Lists are mutable sequences of Python i.e., you can change elements of a list in place. Lists are formed by placing a comma- separated-list of expressions in square brackets. Lists can contain values of mixed data types.
Creating Lists-
X= [2, 6, 8, “ ajay ”]
X=[ ]
The empty list is [ ]. It is equivalent to 0 or ‘ ‘. You can also create an empty list as:
L= list( )
It will generate an empty list and name that list as L.

Nested Lists-

A list can have an element in it, which itself is a list. Such a list is called nested list, e.g.,

L1=[3, 4,[5, 6], 7]
L1 is a nested list with four elements: 3, 4, [5, 6] and 7.
L1[2] element is a list [5,6].
Length of L1 is 4 as it counts [5,6] as one element.

Accessing Individual Elements-

The individual elements of a list are accessed through their indexes

While accessing list elements, if you pass in a negative index, Python adds the length of the list to the index to get element's forward index. That is, for a 6-element list L. L[-5] will be internally computed as: L[-5 +6]= L[1], and so on.

>>>x= [‘c', 'o', 'm', 'p', 'u', 't', 'e']





Comparing Lists-

We can compare two lists using standard comparison operators of Python ,i.e., <, >, ==, !=, etc. Python internally compares individual elements of lists (and tuples) in lexicographical order. (this means that to compare equal, each corresponding element must compare equal and the two sequences must be of the same type i.e., having comparable types of values.)

>>> L1=[1, 2, 3]

>>> L2=[1, 2, 3]

L3=[1, [2, 3]]

>>>L1== L2


>>> L1== L3


List Operations -

Joining lists, replicating list and slicing lists.

Joining Lists- The concatenation operator +, when used with lists, join two lists.





[10, 12,13, 5, 6, 8]

The + operator when used with lists requires that both the operands must be of same type.

>>> L2 * 2

[5, 6, 8, 5, 6, 8]

Replicating or repeating Lists-

We can use * operator to replicate a list specific number of times.

>>> L2= [5, 6, 8]

>>> L2 * 2

[5, 6, 8, 5, 6, 8]

When used with lists, the + operator requires both the operands as list types and

the * operator requires a list and an integer.

Slicing the lists-

like string slices are the sub part of a list exacted out. We can use indexes of list elements to create list slices as per following format:

seq = L [start : stop]

L [start : stop] creates a list slice out of list L with elements fallowing between indexes start and stop , not including stop.

Various operations with lists:

Appending elements to a list-

The append( ) method adds a single item to the end of the list.

>>> lst= [10, 12, 14, 18]

>>> lst.append (16)


[10, 12, 14, 18, 16]

Updating elements to a list-

To update or change an element of the list in place, we just have to assign new value to the element's index in list.

>>> lst= [10, 12, 14, 18]

>>> lst [2]=38


[10, 12, 38, 18, 16]

The pop( ) method is useful only when you want to store the element being deleting for later use, eg.,

x = L.pop() # removes the last element and stores it in x

x= L.pop(0) # removes the first element and stores it in x

x= L.pop(6) # removes the sixth element and stores it in x

The pop( ) method-

The pop() function removes an element from the given position in the list, and return it.. If no index is specified pop() removes and returns the last item in the list.

>>> t1= [‘k', ‘a', ‘e', ‘q', ‘p', 'u']

>>> e1= t1.pop(0)

>>> e1


>>>e2=t1.pop( )




[‘a', ‘e', ‘q', ‘p']

The remove method-

The remove( ) method removes the first occurrence of given item from the list.

Syntax: List .remove(<value>)

It takes one essential argument and does not return anything.

>>> t1= [‘k', ‘a', ‘e', ‘q', ‘k', 'u']



[‘a', ‘e', ‘q', ‘k', 'u ']

The count method-

This function returns the count of the item that you p[assed as argument. If the given item is not in the list, it returns zero.



2     # returns 2 as there are two items with value 18 in the list.



The reverse method-

The reverse( ) method reverses the items of the list. This is done “in place”, i.e., it does not create a new list.

>>> t1= [‘k', ‘a', ‘e', ‘q', ‘k', 'u']

>>>t1.reverse( )


[‘u', 'k', 'q', 'e', 'a', 'k']


Tuple -

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example -

  p=(1, 2, 3, 4, 5)
  q=(‘a', ‘e', ‘ i ', ‘o', ‘u')
  n=(‘Rekha', 104, 98.5)

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists -

tuple = ( ' abcd ', 786 , 2.23, 'john', 70.2 )
list = [ ' abcd ', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000          #   Invalid syntax with tuple
list[2] = 1000           #   Valid syntax with list

Dictionary -

Dictionary data type is an unordered set of comma-separated key:value pairs, within { } , with the requirement that within a dictionary , no two keys can be same. There are unique keys within a directory.
 vow= { ‘a’:1 , ’e’:2 , ‘i’:3, ‘o’:4 , ‘u’:5 }
 Here a, e, i, o, u are the keys of dictionary vow.
 1,2,3,4,5 are values for these keys respectively.

 >>> vow = { ‘a’:1 , ’e’:2 , ‘i’:3, ‘o’:4 , ‘u’:5 }
 >>> vow[‘a’]
 >>> vow [‘u’]
Specifying key inside [ ] after dictionary name give the corresponding value from the key:value pair inside dictionary.



Dictionaries are mutable unordered collections with elements in the form of a key:value pairs that associate keys to values. Rather than having an index associated with each data-item, Dictionaries in Python have a “key” and a “value of that key”.

Dictionaries are containers that associate keys to values. This is, in a way, similar to lists. In lists, you must remember the index value of an element from the list, but with the case of dictionaries, you'll have to know the key to find the element in the dictionaries.

Creating a Dictionary-

<dictionary –name>= {<key>:<value>, <key>:<value> …..}

teacher= {“dimple”: “Computer Science”, “Karan”:”Sociology”, “ Harpreet ”: “mathematics”, “ Saurabh ”: “Legal Studies”}

This as an example of dictionary by the name teacher that stores the names of teachers as keys and the subjects being taught by them as values of respective keys.

Giving Key inside square brackets gives you access only to the value corresponding the mentioned key, mentioning the dictionary name without any square brackets prints/ displays the entire contents of the dictionary.

d= {“Vowel1”: “a”, “Vowel2”:”e”, “Vowel3”:”I”, “Vowel4”:”0”, “Vowel5”:”u”}

>>>d or print(d)

{“Vowel1”: “a”, “Vowel2”:”e”, “Vowel3”:”I”, “Vowel4”:”0”, “Vowel5”:”u”}



A dictionary operation that takes a key and finds the corresponding value, is called lookup.

Accessing Keys or Values Simultaneously-

To see all the keys in a dictionary in one go, we can write <dictionary>.keys()

>>> d.keys ()

dict_keys (‘Vowel1', ‘Vowel2', ‘Vowel3', ‘Vowel4', ‘Vowel5,)

To see all values in one go, we may write <dictionary>.values()

>>> d.values ()

dict_values ([‘a', ‘e', ‘ i ', ‘o', ‘u'])

Internally stored as Mappings- Internally, the key: value pairs of a dictionary are associated with one another with some internal function (called hash- function). This way of linking is called mapping.

Hash - function is an internal algorithm to map and link a key with a value.

Updating Existing Elements in a Dictionary-

In Dictionaries, the updation and addition of elements are similar in syntax. But for addition, the key must not exist in the dictionary and for updation , the key must exist in the dictionary.

employees[‘name']= ‘Ram Lal '

Pop( ) method allows us to specify what to display when the given key does not exist, rather than the default error message.

For example:

>>>employee = {‘ name':'Jackson ', ‘salary':22000, 'age': 24}

>>> employee.pop(‘address', “Not Found”)

‘Not Found'

Checking for existence of a Key-

The in and not in operator check for membership only in keys of the dictionary and not in values. The in operator will return True if the given Key is present in the dictionary. The not in operator will return True if the given Key is not present in the directory.

>>> emp1= { ‘salary':40000, ‘age': 24,'name': 'Mahesh'}

>>>'age' in emp1


>>>'Mahesh' in emp1


>>>'age' not in emp1


However, if you need to search for a value in a directory, then you can use in operator with <dictionary name>.values().

>>> emp1= { ‘salary'=:40000, ‘age': 24,'name': 'Mahesh'}

>>> ‘Mahesh' on emp1.values()


Dictionary Functions and Methods-

The len ( ) method-

It returns length of the dictionary, i.e., count of elements

>>> emp1= { ‘salary':40000, ‘age': 24,'name': 'Mahesh'}

>>> len (emp1)


The clear( ) method-

It removes all the items from the dictionary.

>>> emp1.clear()


{ }

The clear( ) function removes all the elements of a dictionary and makes it empty while del statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no more exists, not even empty dictionary.

>>>del emp1

The get( ) method-

Used to get the item with the given key, also we can specify our own message if the key is not present.

>>> emp1= { ‘salary':40000, ‘age': 24,'name': 'Mahesh'}



>>>emp1.get(‘design', ”Error-Key Not Found”)

‘Error-Key Not Found'

>>> emp1={‘name':'john','salary':'10000,'age':24}




{‘salary':52000,'dept':'computer', ‘name': ‘ Diya ', ‘age': 24}



Tea Or Coffee

Python Downloads

Reindexing and Label Alteration
Function Application –Python pandas
Bar Charts and Histograms and Quantile
Plottint with PyPlot-2


Ways to Keep Your Brain Healthy