Python Datatypes (Tuple, Dictionary and Sets).

Tuple

Tuple is a sequence of objects similar to List but cannot be changed. Unlike list, to define a tuple we have to specify content of tuple separated by comma inside parentheses.

python app

Above we have declared 3 tuples, first tuple consist of combination of strings and number and second one has only numbers and third one is a tuple with single element so we have to end it with comma.

Just like string and list we can access the elements of tuples using slice operators which is what we have done above. We cannot modify the contents inside the tuple, but we can delete an entire tuple using del followed by name of the tuple to delete, followed by semi colon. And when we try to print out the deleted tuple, of course it is going to give us an error and that is what we have got as you see above.

We could add 2 tuples together to create a new tuple as you can see below.

python app

Let us discuss some techniques to evaluate contents inside a tuple.

python app
len(a) Returns the number of values inside a tuple, here in tuple a length is 4.
max(b) Returns the tuple element with maximum value.
min(b) Returns the tuple element with minimum value.
tuple(c) converts a list to tuple

Dictionary

Dictionaries are basically key and value pairs, each key is separated from its value by colon(:), and each key value pair is separated by a commas, and the entire dictionary is enclosed within curly braces.

python app

Above I have created a dictionary called a that has keys from 1 to 5 and each holding the value r,u,b,a and n respectively and I am iterating through each of them using while loop and printing them all out by calling the key, which print out the corresponding value.

Lets say I want to update my dictionary, which can be done by calling the key element of a dictionary and updating it with whatever value we want. Below I have updated value of key 4 from a to e.

python app

Similarly, you can delete a value in dictionary by calling the del dictionary_name[key]. In my code I deleted the key 4 and when I iterated through my dictionary again it is giving me Keyerror saying that key 4 in the dictionary a doesn't exist.

python app

We have a few methods to play with our dictionary a as you can see below, and explanation for that is below the picture.

python app
len(a) returns the number of key-value pairs in the specified dictionary.
str(a) convert the dictionary to string.
type(a) returns the datatype of the variable passed as argument in this case it is dictionary.
a.copy() creates a copy of the entire dictionary.
a.items() returns the items(key value pairs) in a dictionary.
a.keys() returns all keys in the specified dictionary.
a.values() returns all values in the specified dictionary.

In our next chapter we will be discussing about operators in python.