What is Data Structure in Python
Data Structure is a representation that shows relationships between data items. They can be used for storing the data, organizing data, and also defines the operations that can be performed on the data.
List, Dictionary, Tuple, Sets are the built-in data structures available in Python. Data structures like Stack, Queue, Linked lists, Graphs and Trees can be implemented using the built-in data structures.
List – A sequential data structure used to store different data types. A list is written inside square brackets. In a list, the index starts from 0. Python provides various built-in List methods. This includes len()
, append()
, insert(),
pop()
and many more.
>>> li = [1, 2, 4, 'abc', 'xzy']
>>> type(li)
<class 'list'>
Dictionary – Used to store data as Key-Value pairs. A dictionary is an unordered collection. They don’t allow duplicates. Dictionaries are written inside curly brackets with full colon separating key and value.
>>> di = {1:10, 2:'apple', 'color':'red'}
>>> type(di)
<class 'dict'>
Tuple – A tuple is similar to list, but the former is immutable while the latter is mutable. This means that once a tuple is created its elements cannot be changed at a different point in time. A tuple is written inside round brackets with comma separating the elements.
>>> tp = (1, 4, 2, 'red')
>>> type(tp)
<class 'tuple'>
Set – Unordered collection of unique elements. This is similar to sets in mathematics. Sets are written inside curly brackets with comma separating elements.
>>> a= {1, 2, 1}
>>> a
{1, 2}
>>> type(a)
<class 'set'>