In the python tutorial series, we have understood the basics of how to get started to start working in python development. In my last series, we have completed the concept of variables, data types, conditional control, functional control and Module, and packages. Before starting this tutorial I would be recommended to check my last tutorials which are mentioned in above links or you can check form python category to find all python related tutorial that will help you to make strong in python development.
Now in this python tutorial series, we will learn about the Data structures of python. Data structure are used to store a collection of related data. In the category of data structure, we will discuss the Tuple, List, Dictionary, and Set.
1. Tuple
A tuple is a part of the structure and it is similar to List. General difference is that Tuple cannot be changed once it is assigned, while list will change it means we can add or insert item easily. It is declared with parentheses (). We will check some of existing API of the tuple by an example to clearly understand.
#Tuple example my_tuple = (1, 2, 3, 4) print(my_tuple)
Output: (1, 2, 3, 4)
As I said it is not supported while inserting or updating the item of a tuple. Let’s see to add/update an item in a tuple.
my_tuple[0] = (3) print(my_tuple)
Output : TypeError: ‘tuple’ object does not support item assignment
Tuple supports to declare the nested item of any data type.
# nested tuple n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
Let’s see to check some API to manipulate this tuple. How can we get the value from nested tuple?
# nested index print(n_tuple[0][3])
Output: s
# nested index print(n_tuple[1][1])
Output: 4
#slice print(n_tuple[1:4])
Output: ([8, 4, 6], (1, 2, 3))
2. List
A list is the major and important part of the data structure of python. A list can be modified or changed after declared. A list
is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. It can be declared with a square bracket []. Let’s see some of existing API to manipulate the List by an example to clearly understand.
# List example my_list = ['1', '2', '3', '5', '4'] print(my_list)
Output : [‘1’, ‘2’, ‘3’, ‘5’, ‘4’]
# get the first element print(my_list[0])
Output: 1
When we add an item to a list then new item always inserted in the end of the list.
# add the new number or delete my_list.append('6') print(my_list)
Output: [‘1’, ‘2’, ‘3’, ‘5’, ‘4’, ‘6’]
If we want to add an item in between the list then we need to provide the index number where we want to insert the item. So it means other items of right side will be sifted to their position.
# add new number at index my_list.insert(2, '10') print(my_list)
Output: [‘1’, ‘2’, ’10’, ‘3’, ‘5’, ‘4’, ‘6’]
Let’s see few examples of the removed item or pop item from the existing list. A list has properties of the FIFO it mean when we want to pop an item based on index then it will pop from first come first serve.
# delete item my_list.remove('3') print(my_list)
Output: [‘1’, ‘2’, ’10’, ‘5’, ‘4’, ‘6’]
#pop an item my_list.pop(1) print(my_list)
Output: [‘1′, ’10’, ‘5’, ‘4’, ‘6’]
As we know that python is more versetile laungauge. It provides the best maipulation of data. I mean here we can pop the item from the last too. In this case indexing will start from the right side with index 1.
#pop an item from last my_list.pop(-2) print(my_list)
Output: [‘1′, ’10’, ‘5’, ‘6’]
List have existing api for sort the item.
my_list_number = [1, 9, 3, 6, 4] my_list_number.sort() print(my_list_number)
Output: [1, 3, 4, 6, 9]
#nested list my_nested_list = [1, 2, 4, ["Hello", "Buddy"]] print(my_nested_list[3])
Output: [‘Hello’, ‘Buddy’]
We can append item in the nested list too. It will behave like the same as list property.
my_nested_list.append(6) print(my_nested_list)
Output: [1, 2, 4, [‘Hello’, ‘Buddy’], 6]
Now in the last How can we iterate the List?
#Iterate list for x in my_nested_list: print(x)
Output:
1
2
4
[‘Hello’, ‘Buddy’]
6
3. Dictionary
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type in java. Dictionaries are written within curly braces in the form key:value
. This is a very powerful datatype to hold a lot of related information that can be associated through keys
. It is very useful to retrieve data in an optimized way among a large amount of data. In Dictionaries the Key
must be unique.
Dictionaries are created by using braces { } with pairs separated by a comma (,) and the key values associated with a colon(:). Let’s see an example of dictionary and get the data or value from key.
#Dictionary example phonebook = {'joe':'568-564-1109', 'ashish':'657-097-7862'} print(phonebook)
print(phonebook['joe']) print(phonebook['ashish'])
Output: {‘ashish’: ‘657-097-7862’, ‘joe’: ‘568-564-1109’}
Output:
568-564-1109
657-097-7862
#update the value of a key phonebook['joe'] = '1234567' print(phonebook)
Output: {‘ashish’: ‘657-097-7862’, ‘joe’: ‘1234567’}
Now how can we iterate the get the all key of the dictionary and how can we get the key and value togater while iterating the dictionary? Let’s see an example to cleary understand.
# get keys for key in phonebook.keys(): print(key, phonebook[key])
Output:
ashish 657-097-7862
joe 1234567
# get key and value from item for key, value in phonebook.items(): print(key, value)
Output:
ashish 657-097-7862
joe 1234567
In a dictionary, we can delete the data based on the key from the dictionary.
#delete key del(phonebook['joe']) print(phonebook)
Output: {‘ashish’: ‘657-097-7862’}
4. Set
A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. We can add or remove items from it. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. Let’s see few existing APIs to explore set.
# set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set)
Output:
{1, 2, 3}
{‘Hello’, 1.0, (1, 2, 3)}
Generally, we can use the set to find the duplicate item or object Which exists in the list. Let’s me create a List which has the duplicate objects and then I will typecast this list to set to remove the duplicate items.
print("remove duplicates") a = [1,2,3,4,1,2,3] b = set(a) print(b)
Output:
remove duplicates
{1, 2, 3, 4}
Let’s see few examples of union, intersection, symmetric difference by an example to clearly understand.
c = {3,4,5,6} print('union') print(b|c) print (c.union(b))
Output:
union
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
print ('intersection') print (b&c) print (b.intersection(c))
Output:
intersection
{3, 4}
{3, 4}
print ('difference') print( b-c) print (c.difference(b))
Output:
difference
{1, 2}
{5, 6}
print ('symmetric difference') print (b^c) print (c.symmetric_difference(b))
Output:
symmetric difference
{1, 2, 5, 6}
{1, 2, 5, 6}
Summary: Now we have a good understanding of the data structure of python. We have seen few examples and play around it to clear the doubts. If you still having issue or doubts then please add a comment I will try to reply as much possible. In my next python tutorial series, we will learn about the Classes and Objects of python with the example.
If you are wondering to learn Android then Please Learn from Android category and Wondering to lean Kotlin then Kotlin Category will help you. If you want to learn all the python article, then learn from the python category.
Please do subscribe your email to get the newsletter on this blog on below and if you like this post then do not forget to share like and comment on the below section.
Happy coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com