What are basic data structures in python?
Data structures are a very important aspect of any language. Through Data structure we can solve any complex problems. Using data structure we execute our programs faster with minimum time and space complexity.
Python has basic 4 types of inbuilt data structures.
1. List
2. Dictionary
3. Tuple
4. set
Let us brief each one of them.
- List
The list is a very versatile data structure in python. In most cases the list is useful. The list can contain the number, string and even list also. In most cases, we use the list as an array or we can say it like it is a stack. In list we can do an operation like insertion, deletion, slicing, and losts of other functionality. The list is Mutable type of data structure.
Example,
L 1 = [1, “test” , “python” , [1,2]]
print L1
Output:
[1, “test” , “python” , [1,2]] - DictionaryDictionary is very similar to the map in other languages. Dictionary used to store the key, value pair data. Dictionary is used to store JSON kind of data. In the dictionary, there should be a unique key for every value. In some cases, we can define our own class for storing multiple values in the same key. Normally the usage of a dictionary is to create JSON object and get JSON Data. There are lots of functions for the dictionary like get() function, update() function etc.
Example,
D1 = {“name”: “Python”, “type”: “oop Language”}
print D1
Output:{“name”: “Python”, “type”: “oop Language”} - TupleThe tuple is similar to list. normally we can not change the tuple data so it is called an immutable data structure in python. In the list we store data in square brackets and tuple we store data in round brackets. We can do slicing in the tuple. There are few functions that we can perform with tuple like count(), index().
Example,
T1 = (0, 1, 2, 3)
print T1
Output:(0, 1, 2, 3) - SetsSets contain unique data. In set, we store unique data duplicate data can not be stored in sets. we can do operations like union, intersection, etc. Normally we use set for storing the unique data. To create the set we need to call the set() method or by just creating a dictionary with the only keys. We can do the operations like add, remove, etc.
Example,
S1 = {“Python”, “Java”, “Ruby”}
print S1
Output:{‘apple’, ‘cherry’}
No comments: