Data Structures in Python
Data Structures in Python are basically data that a language supports such that it is helpful to define real-life data such as salaries, names of employees and so on. The possibilities are endless. The Data Structures in Python are as shown below:
1.Numeric Data Types
2.Tuple
3.Sets
4.Lists
5.Dictionary
6.String
1. Numeric Data Types
As the name suggests, this is to store numerical data types in the variables. You should know that they are immutable, meaning that the specific data in the variable cannot be changed.
There are 3 numerical data types :
- Integer: This is just as simple to say that you can store integer values in the variables. Ex : a = 10.
- Float: Float holds the real numbers and are represented by a decimal and sometimes even scientific notations with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250). Ex: 10.24.
- Complex Numbers: These are of the form a + bj, where a and b are floats and J represents the square root of -1 (which is an imaginary number). Ex: 10+6j.
1
2
3
|
a = 10 b = 3.142 c = 10 + 6j |
So now that you have understood the various numerical data types, you can understand converting one data type into another data type in this blog of Python Basics.
Type Conversion
Type Conversion is the conversion of a data type into another data type which can be really helpful to us when we start programming to obtain solutions for our problems. Let us understand with examples.
1
2
3
4
|
a = 10 b = 3.142 c = 10 + 6j print ( int (b), float (a), str (c)) |
Output: 10.0 3 ’10+6j’
You can understand, type conversion by the code snippet above. ‘a’ as an integer, ‘b’ as a float and ‘c’ as a complex number. You use the float(), int(), str() methods that are in-built in Python which helps us to convert them. Type Conversion can be really important when you move into real-world examples.
A simple situation could be where you need to compute the salary of the employees in a company and these should be in a float format but they are supplied to us in the string format. So to make our work easier, you just use type conversion and convert the string of salaries into float and then move forward with our work. Now let us head over to the List data type in Python Basics.
2. Lists
List in simple words can be thought of as arrays that exist in other languages but with the exception that they can have heterogeneous elements in them, i.e, differentData Structures in Python in the same list. Lists are mutable, meaning that you can change the data that is available in them.
For those of you who do not know what an array is, you can understand it by imagining a Rack that can hold data in the way you need it to. You can later access the data by calling the position in which it has been stored which is called as Index in a programming language. Lists are defined using either the a=list() method or using a=[] where ‘a’ is the name of the list.
You can see from the above figure, the data that is stored in the list and the index related to that data stored in the list. Note that the Index in Python always starts with ‘0’. You can now move over to the operations that are possible with Lists.
List operations are as shown below in the tabular format.
Code Snippet | Output Obtained | Operation Description |
a[2] | 135 | Finds the data at index 2 and returns it |
a[0:3] | [3.142, ‘Hindi’, 135] | Data from index 0 to 2 is returned as the last index mentioned is always ignored. |
a[3] = ‘eMarathi!’ | moves ‘Marathi!’ to index 3 | The data is replaced in index 3 |
del a[1] | Deletes ‘Hindi’ from the list | Delete items and it does not return any item back |
len(a) | 3 | Obtain the length of a variable in Python |
a * 2 | Output the list ‘a’ twice | If a dictionary is multiplied with a number, it is repeated that many number of times |
a[::-1] | Output the list in the reverse order | Index starts at 0 from left to right. In reverse order, or, right to left, the index starts from -1. |
a.append(3) | 3 will be added at the end of the list | Add data at the end of the list |
a.extend(b) | [3.142, 135, ‘English!’, 3, 2] | ‘b’ is a list with value 2. Adds the data of the list ‘b’ to ‘a’ only. No changes are made to ‘b’. |
a.insert(3,’hello’) | [3.142, 135, ‘English!’, ’hello’, 3, 2] | Takes the index and the value and adds value to that index. |
a.remove(3.142) | [135, ‘English!’, ’hello’, 3, 2] | Removes the value from the list that has been passed as an argument. No value returned. |
a.index(135) | 0 | Finds the element 135 and returns the index of that data |
a.count(‘hello’) | 1 | It goes through the string and finds the times it has been repeated in the list |
a.pop(1) | ‘english!’ | Pops the element in the given index and returns the element if needed. |
a.reverse() | [2, 3, ‘hello’, 135] | It just reverses the list |
a.sort() | [5, 1234, 64738] | Sorts the list based on ascending or descending order. |
a.clear() | [] | Used to remove all the elements that are present in the list. |
Now that you have understood the various list functions, let’s move over to understanding Tuples in Python Basics.
3. Tuples
Tuples in Python are the same as lists. Just one thing to remember, tuples are immutable. That means that once you have declared the tuple, you cannot add, delete or update the tuple. Simple as that. This makes tuples much faster than Lists since they are constant values.
Operations are similar to Lists but the ones where updating, deleting, adding is involved, those operations won’t work. Tuples in Python are written a=() or a=tuple() where ‘a’ is the name of the tuple.
1
2
|
a = ( 'List' , 'Dictionary' , 'Tuple' , 'Integer' , 'Float' ) print (a) |
Output = (‘List’, ‘Dictionary’, ‘Tuple’, ‘Integer’, ‘Float’)
That basically wraps up most of the things that are needed for tuples as you would use them only in cases when you want a list that has a constant value, hence you use tuples. Let us move over to Dictionaries in Python Basics.
4. Dictionary
Dictionary is best understood when you have a real-world example with us. The most easy and well-understood example would be of the telephone directory. Imagine the telephone directory and understand the various fields that exist in it. There is the Name, Phone, E-Mail and other fields that you can think of. Think of the Name as the key and the name that you enter as the value. Similarly, Phone as key, entered data as value. This is what a dictionary is. It is a structure that holds the key, value pairs.
Dictionary is written using either the a=dict() or using a={} where a is a dictionary. The key could be either a string or integer which has to be followed by a “:” and the value of that key.
1
2
3
4
|
MyPhoneBook = { 'Name' : [ 'Akash' , 'Ankita' ] , 'Phone' : [ '12345' , '12354' ] , 'E-Mail' : [ 'akash@rail.com' , 'ankita@rail.com' ]} print (MyPhoneBook) |
Output: { ‘Name’ : [‘Akash’, ‘Ankita’], ‘Phone’ : [‘12345’, ‘12354’], ‘E-Mail’ : [‘akash@rail.com’,’ankita@rail.com’]}
Accessing elements of the Dictionary
You can see that the keys are Name, Phone, and EMail who each have 2 values assigned to them. When you print the dictionary, the key and value are printed. Now if you wanted to obtain values only for a particular key, you can do the following. This is called accessing elements of the dictionary.
1
|
print (MyPhoneBook[ 'E-Mail' ]) |
Output : [‘akash@rail.com’,’ankita@rail.com’]
Operations of Dictionary
Code Snippet | Output Obtained | Operation Description |
MyPhoneBook.keys() | dict_keys([‘Name’, ‘Phone’, ‘E-Mail’]) | Returns all the keys of the dictionary |
MyPhoneBook.values() | dict_values([[‘Akash’, ‘Ankita’], [12345, 12354], [‘ankita@rail.com’, ‘akash@rail.com’]]) | Returns all the values of the dictionary |
MyPhoneBook[‘id’]=[1, 2] | {‘Name’: [‘Akash’, ‘Ankita’], ‘Phone’: [12345, 12354], ‘E-Mail’: [‘ankita@rail.com’, ‘akash@rail.com’], ‘id’: [1, 2]} is the updated value. | The new key, value pair of id is added to the dictionary |
MyPhoneBook[‘Name’][0]=”Akki” | ‘Name’: [‘Akki’, ‘Ankita’] | Access the list of names and change the first element. |
del MyPhoneBook[‘id’] | {‘Name’: [‘Akash’, ‘Ankita’], ‘Phone’: [12345, 12354], ‘E-Mail’: [‘ankita@rail.com’, ‘akash@rail.com’]} | The key, value pair of ID has been deleted |
len(MyPhoneBook) | 3 | 3 key-value pairs in the dictionary and hence you obtain the value 3 |
MyPhoneBook.clear() | {} | Clear the key, value pairs and make a clear dictionary |
You may now have a better understanding of dictionaries in Python Basics. Hence let us move over to Sets in this blog of Python Basics.
5. Sets
A set is basically an un-ordered collection of elements or items. Elements are unique in the set. In Python, they are written inside curly brackets and separated by commas. You can see that even if there are similar elements in set ‘a’, it will still be printed only once because sets are a collection of unique elements.
1
2
3
|
a = { 1 , 2 , 3 , 4 , 4 , 4 } b = { 3 , 4 , 5 , 6 } print (a,b) |
Output : {1, 2, 3, 4} {3, 4, 5, 6}
Operations in Sets
Code Snippet | Output Obtained | Operation Description |
a | b | {1, 2, 3, 4, 5, 6} | Union operation where all the elements of the sets are combined. |
a & b | {3, 4} | Intersection operation where only the elements present in both sets are selected. |
a – b | {1, 2} | Difference operation where the elements present in ‘a’ and ‘b’ are deleted and remaining elements of ‘a’ is the result. |
a ^ b | {1, 2, 5, 6} | Symmetric difference operation where the intersecting elements are deleted and the remaining elements in both sets is the result. |
Sets are simple to understand, so let us move over to strings in Python Basics.
6. Strings
Strings in Python are the most used Data Structures in Python, especially because they are easier for us humans to interact with. They are literally words and letters which makes sense as to how they are being used and in what context. Python hits it out of the park because it has such a powerful integration with strings. Strings are written within a single (‘’) or double quotation marks (“”). Strings are immutable meaning that the data in the string cannot be changed at particular indexes.
The operations of strings with Python can be shown as:
Note: The string here I use is : mystsr =”iceland! is my place”
Code Snippet | Output Obtained | Operation Description |
len(mystr) | 20 | Finds the length of the string |
mystr.index(‘!’) | 7 | Finds the index of the given character in the string |
mystr.count(‘!’) | 1 | Finds the count of the character passed as the parameter |
mystr.upper() | ICELAND! IS MY PLACE | Converts all the string into the upper case |
mystr.split(‘ ‘) | [‘iceland!’, ‘is’, ‘my’, ‘place’] | Breaks the string based on the delimiter passed as the parameter. |
mystr.lower() | iceland! is my place | Converts all the strings of the string into lower case |
mystr.replace(‘ ‘, ‘,’) | iceland!,is,my,place | Replaces the string which has old value with the new value. |
mystr.capitalize() | Iceland! is my place | This capitalizes the first letter of the string |
These are just a few of the functions available and you can find more if you search for it.
Splicing in Strings
Splicing is breaking the string into the format or the way you want to obtain it. For more about this topic, you can read this blog. There are many in-built functions in Python for which you can look up at this article here. That basically sums up the Data Structures in Python in Python. I hope you have a good understanding of the same and if you have any doubts, please leave a comment and I will get back to you as soon as possible.
Related Posts:
Python Tutorial – Learn Python
What is Python? What makes Python so Powerful?
Variables in Python – Constant, Global & Static Variables
Namespacing and Scopes in Python
TUPLE Data Structure in PYTHON
Differences between List and Tuple
DICTIONARY Data Structure in PYTHON
Database Programming in Python
What is Multithreading in Python?
Python Exception Handling Using try, except and finally statement
Lambda Function in PYTHON (Anonymous Function)
Python Interview Question And Answers