Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Python Programming. No Comments on Data Structures in Python Programming
0
(0)

This article provides a comprehensive overview of data structures in Python programming language along with relevant examples.

 

Introduction

A data structure is a construct to store data and organize that data efficiently to perform computations. In Python, data structures can be created using the following types:

 

  • Lists
  • Tuples
  • Sets
  • Dictionaries

 

Lists

 

List is an ordered collection of objects. Lists are mutable. Individual elements in a list are accessed through offset (index). Starting index is zero. Lists are variable-length, heterogeneous, and can be nested.


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


 

Lists are maintained as arrays inside Python interpreter. Not as linked lists. Following are various examples of list literals and functions that can be applied on a list:

 

Operation Description
L = [ ] Empty list
L = [1,3.8,’hai’,[1,2]] A list with four items. Last item is nested list.
L=list(‘Python’) List of iterable items
L=list(range(10)) List of successive integers
L[i] Item at index i
L[i][j] Index of index
L[i:j] Slice from i to j-1
len(L) Length of list L
L1 + L2 Concatenate
L*4 Repeat
8 in L Membership
L.append(10) Appending element at end
L.extend([3, 7, 1]) Extending the list L
L.insert(i, X) Insert element X at index i
L.index(X) Find the index of element X
L.count(X) Count the occurrences of  X in the list
L.sort() Sort the list
L.reverse() Reverse the list
L.copy() Copying the list
L.clear() Empty the list
L.pop(i) Remove and print an item at index i. If index i is not given, it removes and returns the last element.
L.remove(X) Remove an item  X from the list
del L[i] Remove  an item at index i in list L
del L[i:j] Remove all elements from index i to j-1 in list L
L[i:j] = [ ] Remove all elements from index i to j-1 in list L
L[i] = 10 Index assignment
L[i:j] = [2,5,8] Slice assignment
L = [x**2 for x in range(5)] List comprehension
list(map(ord, ‘spam’)) List maps

 

Tuples

 

Tuple is an ordered collection of items. Tuples are immutable. Tuples are fixed in length, heterogeneous, and can be nested. Individual elements can be accessed through offset (index). Following are various examples of tuple literals and functions that can be applied on a tuple:

 

Operation Description
( ) Empty tuple
T = (1,) Tuple with one-item
T = (1,4,6,2) Tuple with four items
T = 1,4,6,2 Same as above. Creates a tuple with four items
T = (2, 6, (4,8)) Nested tuples
T = tuple(‘Python’) Tuple of items in an iterable
T[i] Access tuple item at index i
T[i][j] Access tuple at row index i and column index j
T[i:j] Access a slice of elements in the tuple
len(T) Length of tuple
T1 + T2 Concatenate two tuples
T*3 Repeat tuple elements 3 times
‘hi’ in T Finding membership of ‘hi’ in the tuple
T.index(‘Py’) Returns the index of substring. Otherwise error.
T.Count(‘Py’) Returns the no. of occurences of a item in tuple
namedtuple(‘Emp’, [‘name’, ‘jobs’]) Named tuple extension type

 

The main difference between a list and tuple is, a list is not write protected; i.e., we can add or remove elements from a list. But, a tuple is write protected. Once a tuple is created it is not possible to add or remove elements from it.

 

Sets

 

Set is an unordered collection of unique and immutable objects, i.e., a set cannot contain lists or byte arrays etc. Set itself is mutable. Sets are useful for performing operations corresponding to mathematical set theory. Following are examples of different operations that can be performed on sets:

Consider two sets s1 and se:

 

>>> s1 = {'a','b','c','d'}
>>> s2 = {'c','d','e'}

 

Set difference operation can be performed on sets s1 and s2 as follows:

 

>>> s1-s2
{'a', 'b'}

 

Union operation can be performed on sets s1 and s2 as follows:

 

>>> s1|s2
{'a', 'b', 'c', 'e', 'd'}

 

Intersection operation can be performed on sets s1 and s2 as follows:

 

>>> s1&s2
{'d', 'c'}

 

Symmetric difference can be performed on sets s1 and s2 as follows:

 

>>> s1^s2
{'a', 'b', 'e'}

 

Using the intersection function, we can find the common elements between two sets as follows:

 

>>>s1.intersection(s2)
{'d', 'c'}

 

We can add an element to the set using add function as follows:

 

>>>s2.add('f')
{'f','c','d','e'}

 

An important property of set is, it doesn’t allow duplicate elements. Whenever there is a requirement of storing unique values, we can always use a set.

 

Dictionaries

 

Dictionary is an unordered collection of objects. Objects in a dictionary are accessed through keys instead of by position (like in a list). Dictionaries are mutable, heterogeneous, and nestable. Each key can have only one object associated to it. Internally dictionaries are implemented as hash tables. Following are various examples of dictionary literals and functions that can be applied on dictionaries:

 

Operation Description
D = { } Empty dictionary
D = {‘id’:101, ‘name’:‘Ramesh’} Dictionary with two items
D = {‘name’:{‘fname’:’Ramesh’, ‘lname’:’Kumar’}} Nested dictionaries
D = dict(id=101, name=‘Ramesh’) Alternative way for creating a dictionary
D[‘name’] Indexing by key
D[‘name’][‘lname’] Accessing element in nested dictionary
‘name’ in D Membership test for key
D.keys() Returns all the keys in dictionary
D.values() Returns all values in dictionary
D.items() Returns all key-value tuples
D.copy() Copies a dictionary
D.clear() Empties a dictionary
D.update(D2) Merge by keys
D.popitem() Remove or returns any (key, value) pair
len(D) Returns number of items
D[key] = value Adding/changing keys
del D[key] Deleting entries by key
D={x:x+2 for x in range(10)} Dictionary comprehension

 

A dictionary is unique when compared to other types in Python. In a dictionary each element is made of two things: a key and a value. A dictionary is represented using braces.

 

Sequences

 

A sequence is a positionally ordered collection of objects. Sequences maintain a left-to-right order. Items (objects) are fetched based on their relative position from the left end. Sequences support operations like indexing and slicing. Examples of sequences in Python are: strings, lists, and tuples.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Leave a Reply

Your email address will not be published. Required fields are marked *