Data structures in python

Data is very important in all aspects, the way data is stored and organized so that we can use it in a meaningful way is known as data structures.

In that note python also has very interesting data structures in it, here is the primary summary list,

  1. List
  2. Dict
  3. Set
  4. Tuple

List

List is more likely an array or a sequence of logical elements grouped together.

Elements enclosed with [ ] brackets are known as lists in python.

# Declaring a new list
l = [1, 2, 3, 4, 5]

# Printing the list data structure
print(l)

# Printing type of created list l 
# and this will return as `list`
print(type(l))

# Accessing a list element
# Here we are getting first element of the list
# and this will return 1
print(l[0])

This is a very basic implementation of list, we can do much more with lists.

Dict

Dict is basically a key, value pair. We can assume, key as the variable name holding its value.

Its values are enclosed with { } brackets.

# Initialisation of a new dict 
d = {'first_value': 1, 'second_value': 2}

# Printing the values of variable d
print(d)

# Getting the type of d
# This will return as dict
print(type(d))

# Accessing a key and getting its value 
# This will return as 1 which is the value of key first_value
print(d['first_value'])

This is a very basic implementation of dict, we can do much more with dicts.

Set

It is as same as list, logically grouping of elements. But the prime difference is that unlike list

  1. It doesn’t allow duplicates
  2. It will be ordered list of elements
  3. It doesn’t support indexing

Its values are enclosed with { } brackets.

# Set init
s = {1, 2, 3, 4}

# Printing the type of variable s
print(type(s))

# Now say we have a new set s
s = {1, 10, 1, 3, 4}

# If we just print it we can see that the set is sorted
print(s)
{1, 3, 4, 10}

# Now lets try to access the values via index
print(s[1])

# and here is the error
TypeError Traceback (most recent call last)
<ipython-input-5-f8bb2b116405> in <module>() 1 s[1]

TypeError: 'set' object is not subscriptable
  
# So accessing an element in set will be
# But the order of access will be in the order of
# insertion of the elements
for i in s:
    print(i)
 
# Print results
1
10
3
4

Tuple

Tuple is same as list, logical group of elements. The only difference is that tuples are immutable where a list is mutable.

Its values are enclosed with ( ) brackets

# Tuple init
t = (1, 2, 3, 4)

# Accessing the values of the tuple via index
# and this will return 1 which is the first element 
t[0]

# As tuple is immutable we cannot change values
t[0] = 10
  
# and here is the error
TypeError Traceback (most recent call last)
<ipython-input-4-88963aa635fa> in <module>()
1 t[0] = 10

TypeError: 'tuple' object does not support item assignment

These are base data structures used in python. A few others are Linked List, Queue etc.,

Leave a reply:

Your email address will not be published.