Introduction to Python Data structures

Data structures in Computer Science refer to the storage of data in an organized manner such that it can be accessed and efficiently utilized for various operations.

The Python programming language supports several data structures which are utilized to solve numerous coding problems. In this python data structure tutorial, we are going to learn about different data structures like lists, tuples, dictionaries, and arrays in Python. We will also be covering different operators in Python.

Python Data Structures: List

Lists in Python are non-primitive data structures. They are ordered, mutable or changeable and could store multiple items of different data types in a single variable. The elements of the list are written within a square bracket where each element is separated with a comma. Values in lists can be accessed by their index.

example of python list

Accessing values from python list:

To Access the data items we use indexing :

It starts from 0 to n-1 where n is the no. of items in the list.

The syntax we’ll use will be list_name[index].

Employee_name = [ 'Akash', 'Prakhar', 'Nitish', 'Ayushi', 'Prachi', 'Srijan' ]
Employee_name[1]

‘Prakhar’

We can also use negative indexing to select elements from the end of the list.

We can perform various operations on Python List:

1. Append() Add items at end

In order to add a single item at the end of the existing list, we can use the append() method. It modifies the original list by adding the item to the end of the list instead of creating a new list. This method increases the list of size by one.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
Employee_name.append('Jack')
print(Employee_name)
[‘John’, ‘Doe’, ‘Sebastian’, ‘Doe’, ‘Jack’]

2. Length – Return number of elements.

In order to find out the number of elements present in a list, we can use len() method. This len() method is not specifically for lists but this method can be used with other python data structures.

users = ['John', 'Doe', 'Sebastian','Jack']
len(users)

4

3. Pop – Removes element from specified position.

pop() function in Python programming language removes and returns the last value from the list or the value at a given index. 

We can also pass the index of the element to be popped. 

Employee_name.pop(-1)
print(Employee_name)
[‘Jack’, ‘Sebastian’, ‘Doe’]
Employee_name.pop()
print(Employee_name)
[‘Jack’, ‘Sebastian’]

4. Remove –  Removes first occurrence of an element.

The remove() method in Python removes the first matching element   (which is passed as an argument) from the list.If the element doesn’t exist, it throws ValueError:list.remove(x): x not in list exception.

Employee_name ['John', 'Doe', 'Sebastian', 'Doe']
Employee_name.remove('Doe')
print(Employee_name)
[‘John’, ‘Sebastian’, ‘Doe’]

Python Data Structures: Tuple

Tuples in Python are similar to lists, the major difference between the two is that the tuples are immutable while the lists are mutable. Also, large memory blocks are allocated for tuples as compared to lists which make tuples faster than lists when there are a large number of elements.

Tuples are defined using parentheses ‘()’

python tutorial - creating a python tuple

What are built-in functions with python tuple?

Count() – Returns the number of occurrences of a particular element in a tuple.

The count() function can be used to find how many times a certain element occurs in a tuple.

userid = (101, 102,103,184)
userid.count(101)

1

Index() –  Returns an integer representing the index of an element in the tuple.

Using the index() function, we can find out the position of the element in the tuple. If the same element is present at different positions then the function returns the first instance of the occurrence of that element.

userid (101,102,183,184)
userid.index(103)

2

tuple() – Converts an iterable object like list, string into a tuple

We use tuple() to convert a  list, string into a tuple.

userid = [101,102,103,104]
tuple(userid)

(101, 102, 103, 104)

name = 'Jack'
tuple (name)

(‘3’, ‘a’, ‘c’, ‘k’)

len() 

Similar to lists, this function returns the number of elements present in a tuple

userid = (101, 102,103,184)
len(userid)

4

How to compare tuples in Python?

To compare tuples in Python, a certain set of rules are followed.

Rules:

  1. The n-th items of both tuples (starting with the zero-th index) are compared using the == operator. If both are equal then this step is repeated with the next item.
  2. When two unequal items are present, the item that is “less than” makes the tuple that contains it, also “less than” the other tuple.
  3. If all items are equal then both tuples are equal.
  4. If one tuple runs out of items during step 1 then the shorter tuple is “less than” the longer one.
tuple1 = (1,2,3)
tuple2 = (1,4,2)
tuple1==tuple2, tuplel<tuple2, tuple1>tuple2

(False, True, False)

What is Python Dictionary?

Dictionary in Python is an unordered collection of data values and used to store data in the form of a map, which unlike other data types that hold only a single value as an element.

Dictionary holds key:value pair.

Python programming tutorial - Defining a python dictionary

How to create a dictionary in Python?

There are 2 ways to create a dictionary in Python. 

  1. Defining key value pairs within curly braces ‘{}’
  2. Using dict() constructor
mydict = {'a':1,'b':2, 'c':3}
mydict

{‘a’: 1, ‘b’: 2, ‘c’: 3}

mydict = dict(a=1,b=2,c=3)
mydict

{‘a’: 1, ‘b’: 2, ‘c’: 3}

How to add a key/value pair in a Python dictionary?

We can simply add a new key value pair to a dictionary by using the key as a subscript and assigning it the desired value.

We can also use the update() method to add a new key value pair. 

mydict['d'] = 4
mydict

{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

mydict.update({'e':5})
mydict

{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5}

How to check if a given key already exists in a python dictionary?

To check if a particular key is present in a dictionary or not, we can use a membership operator ‘in’ available to us in Python.

mydict = {'a':1,'b':2, 'c':3}
'a' in mydict, 'key' in mydict

(True, False)

How to sort a dictionary in python?

To sort a dictionary we use the sorted() function.If we want to sort the dictionary by the keys or values, then we need to pass a lambda function along with the dictionaryname.items() variable into the sorted() function.

#In lambda function mention kv[0] first to sort by Keys

mydict = {'b':2, 'c':30, 'a':10}
sorted (mydict.items(), key =
    lambda kv: (kv[0], kv[1]))
[(‘a’, 10), (‘b’, 2), (‘C’, 30)]
#In lambda function mention kv[1] first to sort by values

mydict = {'b':2, 'c':30, 'a':10}
sorted (mydict.items(), key =
   lambda kv: (kv[1], kv[0]))
[(‘b’, 2), (‘a’, 10), (‘c’, 30)]

How to append an element to a key in a dictionary with Python?

We use append() to add elements to the keys in the dictionary. To add an element using append() in a dictionary, we have first to find the key to which we need to append.

details = {'Name':[], 'Class":[]}
details['Name'].append('John')
details

{“Class’: [], ‘Name’: [‘John’]}

[details['class'].append('1eth')
details

{‘Class’: [‘1eth’), ‘Name’: [‘John’]}

How to insert a dictionary into another dictionary in python?

In order to merge the two dictionaries or to insert a dictionary into another dictionary, we can use the update() method.

dict1 = {'a':1,'6":2}
dict2 = {'c':3,'d':4}
dict1. update(dict2)
dict1

{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4

What is Python Array?

Arrays in Python are used to store multiple values in one single variable.

To access arrays in Python, we need to first import the array module.

What is the difference between an array and a list in Python?

ArrayList
An array consists of elements belonging to the same data typeA list can have elements belonging to different data types
Arrays need to be explicitly imported from a module for declarationThe list is a built-in data structure, therefore no need for import declaration
A python array directly handle arithmetic operationsA list cannot directly handle arithmetic operations
An array must contain either all nested elements of the same sizeLists can be nested to contain a different type of elements
Comparatively more compact in-memory sizeConsume larger memory for easy addition of elements

How to define an array in python?

To define an array in Python, we will use array() method. The first argument is the ‘typecode’ or data type of the values stored in an array. The second argument is a list of elements.

import array as arr
a = arr.array('i',[1,2,3])
a

array(‘i’, [1, 2, 3])

Different type codes according to data type can be found here

How to insert elements in array?

To add a particular element at a certain position in an array, we use insert() method. We need to specify 2 arguments, first is the index or position where the element needs to be inserted and second is the element to be inserted.

#insert 4 at index 2

a.insert(2,4)
a

array(‘i’, [1, 2, 4, 3])

How to access array elements in python?

To access array elements, we can use the indexing technique similar to that used for lists and tuples.

a[1], a[-1]

(2, 3)

How to modify or change an element in an array?

To change an element in an array we can use the index as the subscript and assign the new value to that particular index.

a[1] = 100
a

array(‘i’, [1, 100, 4, 3])

How to pop an element from Array in Python?

We can use the pop() method to remove an element from the end of an array. However, we can also pass the index of the element we want to remove.

a.pop(3)

3

a

array(‘i’, [1, 100, 4])

How to search and get the index of a value in an Array?

To search and get the index of an element, we can use the index() method and pass the element we are looking for as an argument.

a.index(100)

1

How to reverse an array in python?

If we want to reverse an array in python, then we can use the built-in reversed() function and pass the object returned by this function along with the typecode into the array() method.

import array as arr
a = arr.array('i',[1,2,3])
reversed_arr = arr.array('i', reversed(a))
reversed_arr

array(‘i’, (3, 2, 1])

How to count the occurrence of a value in Array?

To get the count of the number of occurrences of a particular value we can use count() method.

a = arr.array('i', [1,2,3,1,1])
a.count(1)

3

What are the types of operators in python?

Operators are used to perform operations on variables and values and obtain desired output.

Various Operators available to us in Python are:

1. Arithmetic operators

#Arithmetic operators are used with numeric values to perform common
#mathematical operations

print(10+7, 10-7, 10*7)

17 3 70

2. Assignment operators

#Assignment operators are used to assign values to variables

time_at_venue = 5
time_at_venue += 3
time_at_venue = time_at_venue + 3
print(time_at_venue)

11

3. Comparison operators

#Comparison operators are used to compare two values

distance_a = 10
distance_b = 12

print(distance_a == distance_b, distance_a >= distance_b, distance_a <= distance_b)

False False True

4. Logical operators

#Logical operators are used to combine conditional statements:
and' or 'not'

print(distance_a == distance_b and distance_a <= distance_b)
print(distance_a == distance_b or distance_a <= distance_b)

False
True

5. Identity operators

#Identity operators are used to compare the objects, not if they are equal, but
#if they are actually the same object, with the same memory location

print(distance_a is distance_b, distance_a is not distance_b)

True

6. Membership operators

#Membership operators are used to test if a sequence is presented in an object

weather = 'Humid'
print('mid' in weather)

True

7. Bitwise operators

#Bitwise operators are used to perform bitwise calculations on integers

print(1 ^ 1)
print(1 & 0)
print(1 | 1)

0

0

1

What are logical operators in Python?

In Python, we use Logical operators on conditional statements (either True or False).

Logical ‘AND’: Returns True if both the operands are True

Logical ‘OR’: Returns True if one of the operand is True

Logical ‘NOT’: Returns True if operand is False

if 1<2 and 43:
print('TechLearn)

TechLearn

if 1>2 or 43:
print('TechLearn)

TechLearn

if not(34):
print('TechLearn)

TechLearn

Explore our career paths

TechLearn Career path - Data Scientist
TechLearn career path - Python programmer
TechLearn career path - Deep Learning Engineer

LEAVE A REPLY

Please enter your comment!
Please enter your name here