Please enable JavaScript.
Coggle requires JavaScript to display documents.
Pythonologi - Coggle Diagram
Pythonologi
Data Types
A conditional statement in Python determines the flow of code execution and its direction based on certain conditions. It decides the control flow of a Python program according to the output of the given condition.
Conditional statements
A conditional statement in Python determines the flow of code execution and its direction based on certain conditions. It decides the control flow of a Python program according to the output of the given condition.
Data structures
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages.
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages.
Python Data Structures
In this article, we will discuss the Data Structures in the Python Programming Language and how they are related to some specific Python Data Types. We will discuss all the in-built data structures like list tuples, dictionaries, etc. as well as some advanced data structures like trees, graphs, etc.
Lists
Python Lists are just like the arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.
The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly operation is inserting or deleting the element from the beginning of the List as all the elements are needed to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the preallocated memory becomes full.
We can create a list in python as shown below.
Example: Creating Python List
1
List = [1, 2, 3, "GFG", 2.3]
2
print(List)
Output
[1, 2, 3, 'GFG', 2.3]
List elements can be accessed by the assigned index. In python starting index of the list, sequence is 0 and the ending index is (if N elements are there) N-1.
python-list-slicing
Example: Python List Operations
1
Creating a List with
2
the use of multiple values
3
List = ["Geeks", "For", "Geeks"]
4
print("\nList containing multiple values: ")
5
print(List)
6
7
Creating a Multi-Dimensional List
8
(By Nesting a list inside a List)
9
List2 = [['Geeks', 'For'], ['Geeks']]
10
print("\nMulti-Dimensional List: ")
11
print(List2)
12
13
accessing a element from the
14
list using index number
15
print("Accessing element from the list")
16
print(List[0])
17
print(List[2])
18
19
accessing a element using
20
negative indexing
21
print("Accessing element using negative indexing")
22
23
print the last element of list
24
print(List[-1])
25
26
print the third last element of list
27
print(List[-3])
Output
List containing multiple values:
['Geeks', 'For', 'Geeks']
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Dictionary
Python dictionary is like hash tables in any other language with the time complexity of O(1). It is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in the dictionary to make it more optimized.
Indexing of Python Dictionary is done with the help of keys. These are of any hashable type i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a dictionary by using curly braces ({}) or dictionary comprehension.
Example: Python Dictionary Operations
1
Creating a Dictionary
2
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
3
print("Creating Dictionary: ")
4
print(Dict)
5
6
accessing a element using key
7
print("Accessing a element using key:")
8
print(Dict['Name'])
9
10
accessing a element using get()
11
method
12
print("Accessing a element using get:")
13
print(Dict.get(1))
14
15
creation using Dictionary comprehension
16
myDict = {x: x**2 for x in [1,2,3,4,5]}
17
print(myDict)
Output
Creating Dictionary:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Accessing a element using key:
Geeks
Accessing a element using get:
[1, 2, 3, 4]
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Tuple
Python Tuple is a collection of Python objects much like a list but Tuples are immutable in nature i.e. the elements in the tuple cannot be added or removed once created. Just like a List, a Tuple can also contain elements of various types.
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Example: Python Tuple Operations
1
Creating a Tuple with
2
the use of Strings
3
Tuple = ('Geeks', 'For')
4
print("\nTuple with the use of String: ")
5
print(Tuple)
6
7
Creating a Tuple with
8
the use of list
9
list1 = [1, 2, 4, 5, 6]
10
print("\nTuple using List: ")
11
Tuple = tuple(list1)
12
13
Accessing element using indexing
14
print("First element of tuple")
15
print(Tuple[0])
16
17
Accessing element from last
18
negative indexing
19
print("\nLast element of tuple")
20
print(Tuple[-1])
21
22
print("\nThird last element of tuple")
23
print(Tuple[-3])
Output
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
First element of tuple
1
Last element of tuple
6
Third last element of tuple
4
Set
Python Set is an unordered collection of data that is mutable and does not allow any duplicate element. Sets are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on average.
If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.
Set Implementation:
Internal Working of Set
Sets with Numerous operations on a single HashTable:
Internal Working of Set
Example: Python Set Operations
1
Creating a Set with
2
a mixed type of values
3
(Having numbers and strings)
4
Set = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
5
print("\nSet with the use of Mixed Values")
6
print(Set)
7
8
Accessing element using
9
for loop
10
print("\nElements of set: ")
11
for i in Set:
12
print(i, end =" ")
13
print()
14
15
Checking the element
16
using in keyword
17
print("Geeks" in Set)
Output
Set with the use of Mixed Values
{1, 2, 'Geeks', 4, 6, 'For'}
Elements of set:
1 2 Geeks 4 6 For
True
Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
If no parameters are passed, it returns an empty frozenset.
1
Same as {"a", "b","c"}
2
normal_set = set(["a", "b","c"])
3
4
print("Normal Set")
5
print(normal_set)
6
7
A frozen set
8
frozen_set = frozenset(["e", "f", "g"])
9
10
print("\nFrozen Set")
11
print(frozen_set)
12
13
Uncommenting below line would cause error as
14
we are trying to add element to a frozen set
15
frozen_set.add("h")
Output
Normal Set
{'a', 'c', 'b'}
Frozen Set
frozenset({'g', 'e', 'f'})
String
Python Strings are arrays of bytes representing Unicode characters. In simpler terms, a string is an immutable array of characters. Python does not have a character data type, a single character is simply a string with a length of 1.
Note: As strings are immutable, modifying a string will result in creating a new copy.
strings
Example: Python Strings Operations
1
String = "Welcome to GeeksForGeeks"
2
print("Creating String: ")
3
print(String)
4
5
Printing First character
6
print("\nFirst character of String is: ")
7
print(String[0])
8
9
Printing Last character
10
print("\nLast character of String is: ")
11
print(String[-1])
Output
Creating String:
Welcome to GeeksForGeeks
First character of String is:
W
Last character of String is:
s
Bytearray
Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256.
Example: Python Bytearray Operations
1
Creating bytearray
2
a = bytearray((12, 8, 25, 2))
3
print("Creating Bytearray:")
4
print(a)
5
6
accessing elements
7
print("\nAccessing Elements:", a[1])
8
9
modifying elements
10
a[1] = 3
11
print("\nAfter Modifying:")
12
print(a)
13
14
Appending elements
15
a.append(30)
16
print("\nAfter Adding Elements:")
17
print(a)
Output
Creating Bytearray:
bytearray(b'\x0c\x08\x19\x02')
Accessing Elements: 8
After Modifying:
bytearray(b'\x0c\x03\x19\x02')
After Adding Elements:
bytearray(b'\x0c\x03\x19\x02\x1e')
Till now we have studied all the data structures that come built-in into core Python. Now let dive more deep into Python and see the collections module that provides some containers that are useful in many cases and provide more features than the above-defined functions.
Collections Module
Python collection module was introduced to improve the functionality of the built-in datatypes. It provides various containers let’s see each one of them in detail.
Counters
A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable. This is equivalent to a bag or multiset of other languages.
Example: Python Counter Operations
1
from collections import Counter
2
3
With sequence of items
4
print(Counter(['B','B','A','B','C','A','B','B','A','C']))
5
6
with dictionary
7
count = Counter({'A':3, 'B':5, 'C':2})
8
print(count)
9
10
count.update(['A', 1])
11
print(count)
Output
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 4, 'C': 2, 1: 1})
OrderedDict
An OrderedDict is also a sub-class of dictionary but unlike a dictionary, it remembers the order in which the keys were inserted.
Example: Python OrderedDict Operations
1
from collections import OrderedDict
2
3
print("Before deleting:\n")
4
od = OrderedDict()
5
od['a'] = 1
6
od['b'] = 2
7
od['c'] = 3
8
od['d'] = 4
9
10
for key, value in od.items():
11
print(key, value)
12
13
print("\nAfter deleting:\n")
14
od.pop('c')
15
for key, value in od.items():
16
print(key, value)
17
18
print("\nAfter re-inserting:\n")
19
od['c'] = 3
20
for key, value in od.items():
21
print(key, value)
Output
Before deleting:
a 1
b 2
c 3
d 4
After deleting:
a 1
b 2
d 4
After re-inserting:
a 1
b 2
d 4
c 3
DefaultDict
DefaultDict is used to provide some default values for the key that does not exist and never raises a KeyError. Its objects can be initialized using DefaultDict() method by passing the data type as an argument.
Note: default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised.
Example: Python DefaultDict Operations
1
from collections import defaultdict
2
3
4
Defining the dict
5
d = defaultdict(int)
6
7
L = [1, 2, 3, 4, 2, 4, 1, 2]
8
9
Iterate through the list
10
for keeping the count
11
for i in L:
12
13
The default value is 0
14
so there is no need to
15
enter the key first
16
d[i] += 1
17
18
print(d)
Output
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
ChainMap
A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries. When a key is needed to be found then all the dictionaries are searched one by one until the key is found.
Example: Python ChainMap Operations
1
from collections import ChainMap
2
3
4
d1 = {'a': 1, 'b': 2}
5
d2 = {'c': 3, 'd': 4}
6
d3 = {'e': 5, 'f': 6}
7
8
Defining the chainmap
9
c = ChainMap(d1, d2, d3)
10
print(c)
11
12
print(c['a'])
13
print(c['g'])
Output
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
1
KeyError: 'g'
NamedTuple
A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple.
Example: Python NamedTuple Operations
1
from collections import namedtuple
2
3
Declaring namedtuple()
4
Student = namedtuple('Student',['name','age','DOB'])
5
6
Adding values
7
S = Student('Nandini','19','2541997')
8
9
Access using index
10
print ("The Student age using index is : ",end ="")
11
print (S[1])
12
13
Access using name
14
print ("The Student name using keyname is : ",end ="")
15
print (S.name)
Output
The Student age using index is : 19
The Student name using keyname is : Nandini
Deque
Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to the list with O(n) time complexity.
Python Deque is implemented using doubly linked lists therefore the performance for randomly accessing the elements is O(n).
Example: Python Deque Operations
1
importing "collections" for deque operations
2
import collections
3
4
initializing deque
5
de = collections.deque([1,2,3])
6
7
using append() to insert element at right end
8
inserts 4 at the end of deque
9
de.append(4)
10
11
printing modified deque
12
print("The deque after appending at right is : ")
13
print(de)
14
15
using appendleft() to insert element at left end
16
inserts 6 at the beginning of deque
17
de.appendleft(6)
18
19
printing modified deque
20
print("The deque after appending at left is : ")
21
print(de)
22
23
using pop() to delete element from right end
24
deletes 4 from the right end of deque
25
de.pop()
26
27
printing modified deque
28
print("The deque after deleting from right is : ")
29
print(de)
30
31
using popleft() to delete element from left end
32
deletes 6 from the left end of deque
33
de.popleft()
34
35
printing modified deque
36
print("The deque after deleting from left is : ")
37
print(de)
Output
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
UserDict
UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality.
Example: Python UserDict
1
from collections import UserDict
2
3
Creating a Dictionary where
4
deletion is not allowed
5
class MyDict(UserDict):
6
7
Function to stop deletion
8
from dictionary
9
def
del
(self):
10
raise RuntimeError("Deletion not allowed")
11
12
Function to stop pop from
13
dictionary
14
def pop(self, s = None):
15
raise RuntimeError("Deletion not allowed")
16
17
Function to stop popitem
18
from Dictionary
19
def popitem(self, s = None):
20
raise RuntimeError("Deletion not allowed")
21
22
Driver's code
23
d = MyDict({'a':1,
24
'b': 2,
25
'c': 3})
26
27
print("Original Dictionary")
28
print(d)
29
30
d.pop(1)
Output
Original Dictionary
{'a': 1, 'b': 2, 'c': 3}
RuntimeError: Deletion not allowed
UserList
UserList is a list-like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality.
Examples: Python UserList
1
Python program to demonstrate
2
userlist
3
4
5
from collections import UserList
6
7
8
Creating a List where
9
deletion is not allowed
10
class MyList(UserList):
11
12
Function to stop deletion
13
from List
14
def remove(self, s = None):
15
raise RuntimeError("Deletion not allowed")
16
17
Function to stop pop from
18
List
19
def pop(self, s = None):
20
raise RuntimeError("Deletion not allowed")
21
22
Driver's code
23
L = MyList([1, 2, 3, 4])
24
25
print("Original List")
26
print(L)
27
28
Inserting to List"
29
L.append(5)
30
print("After Insertion")
31
print(L)
32
33
Deleting From List
34
L.remove()
Output
Original List
[1, 2, 3, 4]
After Insertion
[1, 2, 3, 4, 5]
RuntimeError: Deletion not allowed
UserString
UserString is a string-like container and just like UserDict and UserList, it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality.
Example: Python UserString
1
from collections import UserString
2
3
Creating a Mutable String
4
class Mystring(UserString):
5
6
Function to append to
7
string
8
def append(self, s):
9
self.data += s
10
11
Function to remove from
12
string
13
def remove(self, s):
14
self.data = self.data.replace(s, "")
15
16
Driver's code
17
s1 = Mystring("Geeks")
18
print("Original String:", s1.data)
19
20
Appending to string
21
s1.append("s")
22
print("String After Appending:", s1.data)
23
24
Removing from string
25
s1.remove("e")
26
print("String after Removing:", s1.data)
Output
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
Now after studying all the data structures let’s see some advanced data structures such as stack, queue, graph, linked list, etc. that can be used in Python Language.
Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts:
Data
Pointer (Or Reference) to the next node
Example: Defining Linked List in Python
1
Node class
2
class Node:
3
4
Function to initialize the node object
5
def
init
(self, data):
6
self.data = data # Assign data
7
self.next = None # Initialize
8
next as null
9
10
Linked List class
11
class LinkedList:
12
13
Function to initialize the Linked
14
List object
15
def
init
(self):
16
self.head = None
Let us create a simple linked list with 3 nodes.
1
A simple Python program to introduce a linked list
2
3
Node class
4
class Node:
5
6
Function to initialise the node object
7
def
init
(self, data):
8
self.data = data # Assign data
9
self.next = None # Initialize next as null
10
11
12
Linked List class contains a Node object
13
class LinkedList:
14
15
Function to initialize head
16
def
init
(self):
17
self.head = None
18
19
20
Code execution starts here
21
if
name
=='
main
':
22
23
Start with the empty list
24
list = LinkedList()
25
26
list.head = Node(1)
27
second = Node(2)
28
third = Node(3)
29
30
'''
31
Three nodes have been created.
32
We have references to these three blocks as head,
33
second and third
34
35
list.head second third
36
| | |
37
| | |
38
+----+------+ +----+------+ +----+------+
39
| 1 | None | | 2 | None | | 3 | None |
40
+----+------+ +----+------+ +----+------+
41
'''
42
43
list.head.next = second; # Link first node with second
44
45
'''
46
Now next of first Node refers to second. So they
47
both are linked.
48
49
list.head second third
50
| | |
51
| | |
52
+----+------+ +----+------+ +----+------+
53
| 1 | o-------->| 2 | null | | 3 | null |
54
+----+------+ +----+------+ +----+------+
55
'''
56
57
second.next = third; # Link second node with the third node
58
59
'''
60
Now next of second Node refers to third. So all three
61
nodes are linked.
62
63
list.head second third
64
| | |
65
| | |
66
+----+------+ +----+------+ +----+------+
67
| 1 | o-------->| 2 | o-------->| 3 | null |
68
+----+------+ +----+------+ +----+------+
69
'''
Linked List Traversal
In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list.
1
A simple Python program for traversal of a linked list
2
3
Node class
4
class Node:
5
6
Function to initialise the node object
7
def
init
(self, data):
8
self.data = data # Assign data
9
self.next = None # Initialize next as null
10
11
12
Linked List class contains a Node object
13
class LinkedList:
14
15
Function to initialize head
16
def
init
(self):
17
self.head = None
18
19
This function prints contents of linked list
20
starting from head
21
def printList(self):
22
temp = self.head
23
while (temp):
24
print (temp.data)
25
temp = temp.next
26
27
28
Code execution starts here
29
if
name
=='
main
':
30
31
Start with the empty list
32
list = LinkedList()
33
34
list.head = Node(1)
35
second = Node(2)
36
third = Node(3)
37
38
list.head.next = second; # Link first node with second
39
second.next = third; # Link second node with the third node
40
41
list.printList()
Output
1
2
3
Stack
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
Stack in python
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
Python Stack Implementation
Stack in Python can be implemented using the following ways:
list
Collections.deque
queue.LifoQueue
Implementation using List
Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order.
1
stack = []
2
3
append() function to push
4
element in the stack
5
stack.append('g')
6
stack.append('f')
7
stack.append('g')
8
9
print('Initial stack')
10
print(stack)
11
12
pop() function to pop
13
element from stack in
14
LIFO order
15
print('\nElements popped from stack:')
16
print(stack.pop())
17
print(stack.pop())
18
print(stack.pop())
19
20
print('\nStack after elements are popped:')
21
print(stack)
22
23
uncommenting print(stack.pop())
24
will cause an IndexError
25
as the stack is now empty
Output
Initial stack
['g', 'f', 'g']
Elements popped from stack:
g
f
g
Stack after elements are popped:
[]
Implementation using collections.deque:
Python stack can be implemented using the deque class from the collections module. Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
1
from collections import deque
2
3
stack = deque()
4
5
append() function to push
6
element in the stack
7
stack.append('g')
8
stack.append('f')
9
stack.append('g')
10
11
print('Initial stack:')
12
print(stack)
13
14
pop() function to pop
15
element from stack in
16
LIFO order
17
print('\nElements popped from stack:')
18
print(stack.pop())
19
print(stack.pop())
20
print(stack.pop())
21
22
print('\nStack after elements are popped:')
23
print(stack)
24
25
uncommenting print(stack.pop())
26
will cause an IndexError
27
as the stack is now empty
Output
Initial stack:
deque(['g', 'f', 'g'])
Elements popped from stack:
g
f
g
Stack after elements are popped:
deque([])
Implementation using queue module
The queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using the put() function and get() takes data out from the Queue.
1
from queue import LifoQueue
2
3
Initializing a stack
4
stack = LifoQueue(maxsize = 3)
5
6
qsize() show the number of elements
7
in the stack
8
print(stack.qsize())
9
10
put() function to push
11
element in the stack
12
stack.put('g')
13
stack.put('f')
14
stack.put('g')
15
16
print("Full: ", stack.full())
17
print("Size: ", stack.qsize())
18
19
get() function to pop
20
element from stack in
21
LIFO order
22
print('\nElements popped from the stack')
23
print(stack.get())
24
print(stack.get())
25
print(stack.get())
26
27
print("\nEmpty: ", stack.empty())
Output
0
Full: True
Size: 3
Elements popped from the stack
g
f
g
Empty: True
Queue
As a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first.
Queue in Python
Operations associated with queue are:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1)
Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1)
Front: Get the front item from queue – Time Complexity: O(1)
Rear: Get the last item from queue – Time Complexity: O(1)
Python queue Implementation
Queue in Python can be implemented in the following ways:
list
collections.deque
queue.Queue
Implementation using list
Instead of enqueue() and dequeue(), append() and pop() function is used.
1
Initializing a queue
2
queue = []
3
4
Adding elements to the queue
5
queue.append('g')
6
queue.append('f')
7
queue.append('g')
8
9
print("Initial queue")
10
print(queue)
11
12
Removing elements from the queue
13
print("\nElements dequeued from queue")
14
print(queue.pop(0))
15
print(queue.pop(0))
16
print(queue.pop(0))
17
18
print("\nQueue after removing elements")
19
print(queue)
20
21
Uncommenting print(queue.pop(0))
22
will raise and IndexError
23
as the queue is now empty
Output
Initial queue
['g', 'f', 'g']
Elements dequeued from queue
g
f
g
Queue after removing elements
[]
Implementation using collections.deque
Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
1
from collections import deque
2
3
Initializing a queue
4
q = deque()
5
6
Adding elements to a queue
7
q.append('g')
8
q.append('f')
9
q.append('g')
10
11
print("Initial queue")
12
print(q)
13
14
Removing elements from a queue
15
print("\nElements dequeued from the queue")
16
print(q.popleft())
17
print(q.popleft())
18
print(q.popleft())
19
20
print("\nQueue after removing elements")
21
print(q)
22
23
Uncommenting q.popleft()
24
will raise an IndexError
25
as queue is now empty
Output
Initial queue
deque(['g', 'f', 'g'])
Elements dequeued from the queue
g
f
g
Queue after removing elements
deque([])
Implementation using the queue.Queue
queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means an infinite queue. This Queue follows the FIFO rule.
1
from queue import Queue
2
3
Initializing a queue
4
q = Queue(maxsize = 3)
5
6
qsize() give the maxsize
7
of the Queue
8
print(q.qsize())
9
10
Adding of element to queue
11
q.put('g')
12
q.put('f')
13
q.put('g')
14
15
Return Boolean for Full
16
Queue
17
print("\nFull: ", q.full())
18
19
Removing element from queue
20
print("\nElements dequeued from the queue")
21
print(q.get())
22
print(q.get())
23
print(q.get())
24
25
Return Boolean for Empty
26
Queue
27
print("\nEmpty: ", q.empty())
28
29
q.put(1)
30
print("\nEmpty: ", q.empty())
31
print("Full: ", q.full())
32
33
This would result into Infinite
34
Loop as the Queue is empty.
35
print(q.get())
Output
0
Full: True
Elements dequeued from the queue
g
f
g
Empty: True
Empty: False
Full: False
Priority Queue
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties.
An element with high priority is dequeued before an element with low priority.
If two elements have the same priority, they are served according to their order in the queue.
1
A simple implementation of Priority Queue
2
using Queue.
3
class PriorityQueue(object):
4
def
init
(self):
5
self.queue = []
6
7
def
str
(self):
8
return ' '.join([str(i) for i in self.queue])
9
10
for checking if the queue is empty
11
def isEmpty(self):
12
return len(self.queue) == 0
13
14
for inserting an element in the queue
15
def insert(self, data):
16
self.queue.append(data)
17
18
for popping an element based on Priority
19
def delete(self):
20
try:
21
max = 0
22
for i in range(len(self.queue)):
23
if self.queue[i] > self.queue[max]:
24
max = i
25
item = self.queue[max]
26
del self.queue[max]
27
return item
28
except IndexError:
29
print()
30
exit()
31
32
if
name
== '
main
':
33
myQueue = PriorityQueue()
34
myQueue.insert(12)
35
myQueue.insert(1)
36
myQueue.insert(14)
37
myQueue.insert(7)
38
print(myQueue)
39
while not myQueue.isEmpty():
40
print(myQueue.delete())
Output
12 1 14 7
14
12
7
1
Heap queue (or heapq)
heapq module in Python provides the heap data structure that is mainly used to represent a priority queue. The property of this data structure in Python is that each time the smallest heap element is popped(min-heap). Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest element each time.
It supports the extraction and insertion of the smallest element in the O(log n) times.
1
importing "heapq" to implement heap queue
2
import heapq
3
4
initializing list
5
li = [5, 7, 9, 1, 3]
6
7
using heapify to convert list into heap
8
heapq.heapify(li)
9
10
printing created heap
11
print ("The created heap is : ",end="")
12
print (list(li))
13
14
using heappush() to push elements into heap
15
pushes 4
16
heapq.heappush(li,4)
17
18
printing modified heap
19
print ("The modified heap after push is : ",end="")
20
print (list(li))
21
22
using heappop() to pop smallest element
23
print ("The popped and smallest element is : ",end="")
24
print (heapq.heappop(li))
Output
The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [1, 3, 4, 7, 5, 9]
The popped and smallest element is : 1
Binary Tree
A tree is a hierarchical data structure that looks like the below figure –
tree
j <-- root
/ \
f k
/ \ \
a h z <-- leaves
The topmost node of the tree is called the root whereas the bottommost nodes or the nodes with no children are called the leaf nodes. The nodes that are directly under a node are called its children and the nodes that are directly above something are called its parent.
A binary tree is a tree whose elements can have almost two children. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. A Binary Tree node contains the following parts.
Data
Pointer to left child
Pointer to the right child
Example: Defining Node Class
1
A Python class that represents an individual node
2
in a Binary Tree
3
class Node:
4
def
init
(self,key):
5
self.left = None
6
self.right = None
7
self.val = key
Now let’s create a tree with 4 nodes in Python. Let’s assume the tree structure looks like below –
tree
1 <-- root
/ \
2 3
/
4
Example: Adding data to the tree
1
Python program to introduce Binary Tree
2
3
A class that represents an individual node in a
4
Binary Tree
5
class Node:
6
def
init
(self,key):
7
self.left = None
8
self.right = None
9
self.val = key
10
11
12
create root
13
root = Node(1)
14
''' following is the tree after above statement
15
1
16
/ \
17
None None'''
18
19
root.left = Node(2);
20
root.right = Node(3);
21
22
''' 2 and 3 become left and right children of 1
23
1
24
/ \
25
2 3
26
/ \ / \
27
None None None None'''
28
29
30
root.left.left = Node(4);
31
'''4 becomes left child of 2
32
1
33
/ \
34
2 3
35
/ \ / \
36
4 None None None
37
/ \
38
None None'''
Tree Traversal
Trees can be traversed in different ways. Following are the generally used ways for traversing trees. Let us consider the below tree –
tree
1 <-- root
/ \
2 3
/ \
4 5
Depth First Traversals:
Inorder (Left, Root, Right) : 4 2 5 1 3
Preorder (Root, Left, Right) : 1 2 4 5 3
Postorder (Left, Right, Root) : 4 5 2 3 1
Algorithm Inorder(tree)
Traverse the left subtree, i.e., call Inorder(left-subtree)
Visit the root.
Traverse the right subtree, i.e., call Inorder(right-subtree)
Algorithm Preorder(tree)
Visit the root.
Traverse the left subtree, i.e., call Preorder(left-subtree)
Traverse the right subtree, i.e., call Preorder(right-subtree)
Algorithm Postorder(tree)
Traverse the left subtree, i.e., call Postorder(left-subtree)
Traverse the right subtree, i.e., call Postorder(right-subtree)
Visit the root.
1
Python program to for tree traversals
2
3
A class that represents an individual node in a
4
Binary Tree
5
class Node:
6
def
init
(self, key):
7
self.left = None
8
self.right = None
9
self.val = key
10
11
12
A function to do inorder tree traversal
13
def printInorder(root):
14
15
if root:
16
17
First recur on left child
18
printInorder(root.left)
19
20
then print the data of node
21
print(root.val),
22
23
now recur on right child
24
printInorder(root.right)
25
26
27
A function to do postorder tree traversal
28
def printPostorder(root):
29
30
if root:
31
32
First recur on left child
33
printPostorder(root.left)
34
35
the recur on right child
36
printPostorder(root.right)
37
38
now print the data of node
39
print(root.val),
40
41
42
A function to do preorder tree traversal
43
def printPreorder(root):
44
45
if root:
46
47
First print the data of node
48
print(root.val),
49
50
Then recur on left child
51
printPreorder(root.left)
52
53
Finally recur on right child
54
printPreorder(root.right)
55
56
57
Driver code
58
root = Node(1)
59
root.left = Node(2)
60
root.right = Node(3)
61
root.left.left = Node(4)
62
root.left.right = Node(5)
63
print("Preorder traversal of binary tree is")
64
printPreorder(root)
65
66
print("\nInorder traversal of binary tree is")
67
printInorder(root)
68
69
print("\nPostorder traversal of binary tree is")
70
printPostorder(root)
Output
Preorder traversal of binary tree is
1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5
2
3
1
Time Complexity – O(n)
Breadth-First or Level Order Traversal
Level order traversal of a tree is breadth-first traversal for the tree. The level order traversal of the above tree is 1 2 3 4 5.
For each node, first, the node is visited and then its child nodes are put in a FIFO queue. Below is the algorithm for the same –
Create an empty queue q
temp_node = root /
start from root
/
Loop while temp_node is not NULL
print temp_node->data.
Enqueue temp_node’s children (first left then right children) to q
Dequeue a node from q
1
Python program to print level
2
order traversal using Queue
3
4
A node structure
5
class Node:
6
7
A utility function to create a new node
8
def
init
(self ,key):
9
self.data = key
10
self.left = None
11
self.right = None
12
13
Iterative Method to print the
14
height of a binary tree
15
def printLevelOrder(root):
16
17
Base Case
18
if root is None:
19
return
20
21
Create an empty queue
22
for level order traversal
23
queue = []
24
25
Enqueue Root and initialize height
26
queue.append(root)
27
28
while(len(queue) > 0):
29
30
Print front of queue and
31
remove it from queue
32
print (queue[0].data)
33
node = queue.pop(0)
34
35
Enqueue left child
36
if node.left is not None:
37
queue.append(node.left)
38
39
Enqueue right child
40
if node.right is not None:
41
queue.append(node.right)
42
43
Driver Program to test above function
44
root = Node(1)
45
root.left = Node(2)
46
root.right = Node(3)
47
root.left.left = Node(4)
48
root.left.right = Node(5)
49
50
print ("Level Order Traversal of binary tree is -")
51
printLevelOrder(root)
Output
Level Order Traversal of binary tree is -
1
2
3
4
5
Time Complexity: O(n)
Graph
A graph is a nonlinear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes.
In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}.
The following two are the most commonly used representations of a graph.
Adjacency Matrix
Adjacency List
Adjacency Matrix
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. The adjacency matrix for an undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
1
A simple representation of graph using Adjacency Matrix
2
class Graph:
3
def
init
(self,numvertex):
4
self.adjMatrix = [[-1]*numvertex for x in range(numvertex)]
5
self.numvertex = numvertex
6
self.vertices = {}
7
self.verticeslist =[0]*numvertex
8
9
def set_vertex(self,vtx,id):
10
if 0<=vtx<=self.numvertex:
11
self.vertices[id] = vtx
12
self.verticeslist[vtx] = id
13
14
def set_edge(self,frm,to,cost=0):
15
frm = self.vertices[frm]
16
to = self.vertices[to]
17
self.adjMatrix[frm][to] = cost
18
19
for directed graph do not add this
20
self.adjMatrix[to][frm] = cost
21
22
def get_vertex(self):
23
return self.verticeslist
24
25
def get_edges(self):
26
edges=[]
27
for i in range (self.numvertex):
28
for j in range (self.numvertex):
29
if (self.adjMatrix[i][j]!=-1):
30
edges.append((self.verticeslist[i],self.verticeslist[j],self.adjMatrix[i][j]))
31
return edges
32
33
def get_matrix(self):
34
return self.adjMatrix
35
36
G =Graph(6)
37
G.set_vertex(0,'a')
38
G.set_vertex(1,'b')
39
G.set_vertex(2,'c')
40
G.set_vertex(3,'d')
41
G.set_vertex(4,'e')
42
G.set_vertex(5,'f')
43
G.set_edge('a','e',10)
44
G.set_edge('a','c',20)
45
G.set_edge('c','b',30)
46
G.set_edge('b','e',40)
47
G.set_edge('e','d',50)
48
G.set_edge('f','e',60)
49
50
print("Vertices of Graph")
51
print(G.get_vertex())
52
53
print("Edges of Graph")
54
print(G.get_edges())
55
56
print("Adjacency Matrix of Graph")
57
print(G.get_matrix())
Output
Vertices of Graph
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
Edges of Graph
[(‘a’, ‘c’, 20), (‘a’, ‘e’, 10), (‘b’, ‘c’, 30), (‘b’, ‘e’, 40), (‘c’, ‘a’, 20), (‘c’, ‘b’, 30), (‘d’, ‘e’, 50), (‘e’, ‘a’, 10), (‘e’, ‘b’, 40), (‘e’, ‘d’, 50), (‘e’, ‘f’, 60), (‘f’, ‘e’, 60)]
Adjacency Matrix of Graph
[[-1, -1, 20, -1, 10, -1], [-1, -1, 30, -1, 40, -1], [20, 30, -1, -1, -1, -1], [-1, -1, -1, -1, 50, -1], [10, 40, -1, 50, -1, 60], [-1, -1, -1, -1, 60, -1]]
Adjacency List
An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph.
Adjacency List Representation of Graph
1
A class to represent the adjacency list of the node
2
class AdjNode:
3
def
init
(self, data):
4
self.vertex = data
5
self.next = None
6
7
8
A class to represent a graph. A graph
9
is the list of the adjacency lists.
10
Size of the array will be the no. of the
11
vertices "V"
12
class Graph:
13
def
init
(self, vertices):
14
self.V = vertices
15
self.graph = [None] * self.V
16
17
Function to add an edge in an undirected graph
18
def add_edge(self, src, dest):
19
20
Adding the node to the source node
21
node = AdjNode(dest)
22
node.next = self.graph[src]
23
self.graph[src] = node
24
25
Adding the source node to the destination as
26
it is the undirected graph
27
node = AdjNode(src)
28
node.next = self.graph[dest]
29
self.graph[dest] = node
30
31
Function to print the graph
32
def print_graph(self):
33
for i in range(self.V):
34
print("Adjacency list of vertex {}\n head".format(i), end="")
35
temp = self.graph[i]
36
while temp:
37
print(" -> {}".format(temp.vertex), end="")
38
temp = temp.next
39
print(" \n")
40
41
42
Driver program to the above graph class
43
if
name
== "
main
":
44
V = 5
45
graph = Graph(V)
46
graph.add_edge(0, 1)
47
graph.add_edge(0, 4)
48
graph.add_edge(1, 2)
49
graph.add_edge(1, 3)
50
graph.add_edge(1, 4)
51
graph.add_edge(2, 3)
52
graph.add_edge(3, 4)
53
54
graph.print_graph()
Output
Adjacency list of vertex 0
head -> 4 -> 1
Adjacency list of vertex 1
head -> 4 -> 3 -> 2 -> 0
Adjacency list of vertex 2
head -> 3 -> 1
Adjacency list of vertex 3
head -> 4 -> 2 -> 1
Adjacency list of vertex 4
head -> 3 -> 1 -> 0
Graph Traversal
Breadth-First Search or BFS
Breadth-First Traversal for a graph is similar to Breadth-First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth-First Traversal of the following graph is 2, 0, 3, 1.
1
Python3 Program to print BFS traversal
2
from a given source vertex. BFS(int s)
3
traverses vertices reachable from s.
4
from collections import defaultdict
5
6
This class represents a directed graph
7
using adjacency list representation
8
class Graph:
9
10
Constructor
11
def
init
(self):
12
13
default dictionary to store graph
14
self.graph = defaultdict(list)
15
16
function to add an edge to graph
17
def addEdge(self,u,v):
18
self.graph[u].append(v)
19
20
Function to print a BFS of graph
21
def BFS(self, s):
22
23
Mark all the vertices as not visited
24
visited = [False] * (max(self.graph) + 1)
25
26
Create a queue for BFS
27
queue = []
28
29
Mark the source node as
30
visited and enqueue it
31
queue.append(s)
32
visited[s] = True
33
34
while queue:
35
36
Dequeue a vertex from
37
queue and print it
38
s = queue.pop(0)
39
print (s, end = " ")
40
41
Get all adjacent vertices of the
42
dequeued vertex s. If a adjacent
43
has not been visited, then mark it
44
visited and enqueue it
45
for i in self.graph[s]:
46
if visited[i] == False:
47
queue.append(i)
48
visited[i] = True
49
50
Driver code
51
52
Create a graph given in
53
the above diagram
54
g = Graph()
55
g.addEdge(0, 1)
56
g.addEdge(0, 2)
57
g.addEdge(1, 2)
58
g.addEdge(2, 0)
59
g.addEdge(2, 3)
60
g.addEdge(3, 3)
61
62
print ("Following is Breadth First Traversal"
63
" (starting from vertex 2)")
64
g.BFS(2)
65
66
This code is contributed by Neelam Yadav
Output
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
Time Complexity: O(V+E) where V is the number of vertices in the graph and E is the number of edges in the graph.
Depth First Search or DFS
Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array.
Algorithm:
Create a recursive function that takes the index of the node and a visited array.
Mark the current node as visited and print the node.
Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.
1
Python3 program to print DFS traversal
2
from a given graph
3
from collections import defaultdict
4
5
This class represents a directed graph using
6
adjacency list representation
7
8
9
class Graph:
10
11
Constructor
12
def
init
(self):
13
14
default dictionary to store graph
15
self.graph = defaultdict(list)
16
17
function to add an edge to graph
18
def addEdge(self, u, v):
19
self.graph[u].append(v)
20
21
A function used by DFS
22
def DFSUtil(self, v, visited):
23
24
Mark the current node as visited
25
and print it
26
visited.add(v)
27
print(v, end=' ')
28
29
Recur for all the vertices
30
adjacent to this vertex
31
for neighbour in self.graph[v]:
32
if neighbour not in visited:
33
self.DFSUtil(neighbour, visited)
34
35
The function to do DFS traversal. It uses
36
recursive DFSUtil()
37
def DFS(self, v):
38
39
Create a set to store visited vertices
40
visited = set()
41
42
Call the recursive helper function
43
to print DFS traversal
44
self.DFSUtil(v, visited)
45
46
Driver code
47
48
49
Create a graph given
50
in the above diagram
51
g = Graph()
52
g.addEdge(0, 1)
53
g.addEdge(0, 2)
54
g.addEdge(1, 2)
55
g.addEdge(2, 0)
56
g.addEdge(2, 3)
57
g.addEdge(3, 3)
58
59
print("Following is DFS from (starting from vertex 2)")
60
g.DFS(2)
Output
Following is DFS from (starting from vertex 2)
2 0 1 3
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Python Data Structures – FAQs
What Are the Basic Data Structures in Python?
Python provides several built-in data structures that are used to store collections of data. These include:
List: An ordered collection of items which can be of different types. Lists are mutable.
my_list = [1, 2, 3, "four"]
Tuple: An ordered collection of items which can be of different types. Tuples are immutable.
my_tuple = (1, 2, 3, "four")
Set: An unordered collection of unique items. Sets are mutable.
my_set = {1, 2, 3, 4}
Dictionary: An unordered collection of key-value pairs. Dictionaries are mutable.
my_dict = {"one": 1, "two": 2, "three": 3}
String: A sequence of characters. Strings are immutable.
my_string = "Hello, World!"
What Are Mutable and Immutable Data Structures?
Mutable Data Structures: These are data structures that can be modified after creation. Examples include lists, dictionaries, and sets.Example:
my_list = [1, 2, 3]
my_list.append(4) # my_list is now [1, 2, 3, 4]
Immutable Data Structures: These are data structures that cannot be modified after creation. Examples include strings, tuples, and frozensets.Example:
my_tuple = (1, 2, 3)
my_tuple[0] = 4 # This will raise a TypeError
How to Choose the Right Data Structure in Python?
Choosing the right data structure depends on the specific needs of your application. Consider the following factors:
Access Speed:
Lists provide O(1) time complexity for indexing.
Dictionaries provide O(1) time complexity for key lookup.
Insertion and Deletion:
Lists have O(n) time complexity for insertion and deletion in the worst case.
Sets and dictionaries have O(1) time complexity for insertion and deletion.
Order:
Lists and tuples maintain the order of elements.
Sets and dictionaries (in Python 3.7+) maintain insertion order, but typically sets are considered unordered collections.
Uniqueness:
Sets ensure all elements are unique.
Lists and tuples allow duplicate elements.
Mutability:
If you need to modify the data structure after creation, use mutable structures like lists or dictionaries.
For fixed collections of items, use immutable structures like tuples or frozensets.
What Are Data Structures Available in the collections Module?
The collections module in Python provides several additional data structures that are designed to handle specific use cases:
namedtuple(): Factory function for creating tuple subclasses with named fields.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
deque: A list-like container with fast appends and pops on both ends.
from collections import deque
d = deque([1, 2, 3])
d.append(4)
d.appendleft(0)
ChainMap: A class for creating a single view of multiple mappings.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
chain = ChainMap(dict1, dict2)
Counter: A dictionary subclass for counting hashable objects.
from collections import Counter
cnt = Counter(['a', 'b', 'c', 'a', 'b', 'b'])
OrderedDict: A dictionary subclass that remembers the order entries were added.
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
defaultdict: A dictionary subclass that calls a factory function to supply missing values.
from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1
Why is DSA Important ?
Visit Course
explore course icon
Video Thumbnail
Why is DSA Important ?
Video Thumbnail
List (Dynamic Sized Array) Introduction
Video Thumbnail
Recursion in Python
Video Thumbnail
Binary Search in Python
Video Thumbnail
Python String
Video Thumbnail
Stack in Python
Video Thumbnail
Queue in Python
Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!
Comment
More info
Placement Training Program
Next Article
Create Pandas Dataframe from Dictionary of Dictionaries
Similar Reads
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Inbuilt Data Structures in Python
Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics. Above mentioned topics are divided into four sections below. Lists: Lists in Python are one of the most versatile collection object types ava
3 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
Internal implementation of Data Structures in Python
Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementations: Data Structure Internal Implementation Static o
3 min read
Python Data Structures Quizzes
This quiz is designed to test your understanding of Python's data structures, such as list, strings, tuples, sets and dictionaries. By practicing, you’ll reinforce your knowledge and gain confidence in identifying, using and these data structures of Python. Data Structures QuizPython ListStringTuplesDictionarySetArrays
1 min read
Data Structures in Pandas
Pandas is an open-source library that uses for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. It offers a tool for cleaning and processes your data. It is the most popular Python library that is used for data analysis. In this a
4 min read
scipy.spatial - Spatial data structures and algorithms
In this article, we are going to see spatial data structure and algorithms, it is used to represent data in a geometric space. What is spatial data structure? The spatial package computes the triangulations, Voronoi diagrams, and convex hulls of a set of points, by leveraging the Qhull library. Moreover, it contains KDTree implementations for neare
2 min read
Converting nested JSON structures to Pandas DataFrames
In this article, we are going to see how to convert nested JSON structures to Pandas DataFrames. JSON with multiple levels In this case, the nested JSON data contains another JSON object as the value for some of its attributes. This makes the data multi-level and we need to flatten it as per the project requirements for better readability, as expla
3 min read
How to convert unstructured data to structured data using Python ?
Prerequisite: What is Unstructured Data? Sometimes machine generates data in an unstructured way which is less interpretable. For example, Biometric Data, where an employee does Punch - IN or OUT several times with mistakes. We can not analyze the data and identify the mistakes unless it's in a tabular form. In this article, we will take unstructur
5 min read
Python - Convert Tick-by-Tick data into OHLC (Open-High-Low-Close) Data
In this post, we'll explore a Python pandas package feature. We frequently find queries about converting tick-by-tick data to OHLC (Open, High, Low and Close). Using pandas kit this can be done with minimum effort. The OHLC data is used over a unit of time (1 day, 1 hour etc.) to perform a technical analysis of price movement. The First Step: The f
2 min read
How to convert categorical data to binary data in Python?
Categorical Data is data that corresponds to the Categorical Variable. A Categorical Variable is a variable that takes fixed, a limited set of possible values. For example Gender, Blood group, a person having country residential or not, etc. Characteristics of Categorical Data : This is mostly used in Statistics.Numerical Operation like Addition, S
4 min read
Primitive Data Types vs Non Primitive Data Types in Python
Python, known for its versatility and user-friendliness, is a dynamic language that doesn't explicitly categorize data types into primitive and non-primitive as some languages like Java do. However, for clarity and understanding, it's useful to draw parallels and discuss similar concepts. In this article, we'll explore the types of data types tradi
4 min read
Does Dark Data Have Any Worth In The Big Data World?
Big Data is the new oil in modern times!!! And those companies that can analyze this data for actionable insights are the new super-rich!!! More and more companies are understanding this fact and investing in Big Data Analytics. So much so that this number has reached 53% in 2017, which is a huge growth from 17% in 2015. But Big Data is of multiple
5 min read
Training data vs Testing data
There are two key types of data used for machine learning training and testing data. They each have a specific function to perform when building and evaluating machine learning models. Machine learning algorithms are used to learn from data in datasets. They discover patterns and gain knowledge. make choices, and examine those decisions. In this ar
7 min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or
) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass
hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
MongoDB Python | Insert and Update Data
Prerequisites : MongoDB Python Basics We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection. Insert data We would
3 min read
MongoDB python | Delete Data and Drop Collection
Prerequisite : MongoDB Basics, Insert and Update Aim : To delete entries/documents of a collection in a database. Assume name of collection 'my_collection'. Method used : delete_one() or delete_many() Remove All Documents That Match a Condition : The following operation removes all documents that match the specified condition. result = my_collectio
2 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
Replacing strings with numbers in Python for Data Analysis
Sometimes we need to convert string values in a pandas dataframe to a unique integer so that the algorithms can perform better. So we assign unique numeric value to a string value in Pandas DataFrame. Note: Before executing create an example.csv file containing some names and gender Say we have a table containing names and gender column. In gender
3 min read
course-img
34k+ interested Geeks
Complete Data Analytics Program
Avail 90% Refund
course-img
77k+ interested Geeks
DSA for Interview Preparation
Avail 90% Refund
course-img
243k+ interested Geeks
Python Full Course Online - Complete Beginner to Advanced
Avail 90% Refund
course-img
310k+ interested Geeks
Data Structures & Algorithms in Python - Self Paced
Avail 90% Refund
course-img
14k+ interested Geeks
CBSE Class 12 Computer Science
Avail 90% Refund
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store
GFG App on App Store
Advertise with us
Company
About Us
Legal
Privacy Policy
Careers
In Media
Contact Us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning
ML Maths
Data Visualisation
Pandas
NumPy
NLP
Deep Learning
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Pre-defined functions
A pre-defined function is built into the software and does not need to be created by a programmer
Loops
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.