Python Installation - A Quick Guide
Python, a powerful and versatile programming language, serves as a foundation for countless applications. Here's a brief guide on installing Python:
Download Python:
Visit the official Python website (https://www.python.org/).
Navigate to the "Downloads" section.
Choose the appropriate version for your operating system (Windows, macOS, or Linux).
Follow the installation instructions provided on the website.
Verify Installation:
Open a terminal or command prompt.
Type
python --version
orpython -V
and press Enter.If installed correctly, you'll see the installed Python version.
Now that you have Python installed, let's delve into the fundamental concepts of data structures.
Data Structures and Types in Python
Data structures are crucial for organizing and storing data efficiently. In Python, we have two main types:
Primitive Data Structures
Integer:
- Whole numbers without decimals.
num = 42
Float:
- Real numbers with decimals.
float_num = 3.14
String:
- Sequences of characters.
name="Ansar" # combination of charectors "'A' 'n' 's' 'a' 'r'"
# [0] [1] [2] [3] [4]
print(len(name)) #leangth of string
# slicing of string
print(name[0:5]) # first to last
print(name[::-1]) # gives reverse of string
print(name[2:0:-1]) #for s
Boolean:
- Represents True or False values.
is_python_fun = True
Type Casting
Type casting allows conversion between different data types.
# Example of type casting
#--------Explicit----------------------------------------------------------
marks=100 #int
marks_float=float(marks) #converted to float
print(type(marks_float))
#---------implicit-----------------------------------------------------------------
num=20 #int
den=5.0 #Float
div=num/den #implicit Type Casting
print(div,type(div)) #4.0 <class 'float'> Priority will be given to float
Non-Primitive Data Structures
1. List and Operations
Lists are versatile, mutable collections of items.
Iteration using For Loop:
list1=[] print(type(list1)) # Anything inside [] is a list # Methods to create a list # Method-1 my_list_1=[1,2.5,'hello'] # Method-2 my_list_2=list() #by using list function print(type(my_list_1)) # Methos-1 is Faster print(type(my_list_2))
list_of_fruits=['apple','kiwi','mango','banana','orange'] list_of_animals=['dog','cat','hen','goat','lion'] list_of_numbers=[1,2,2,3,5,7,45,2,5,7,8,45,800] #-----List Operations---------- list_of_animals.append('Tiger') # append() will append 'Tiger' at the end of list print(list_of_numbers.count(2)) # count() gives the count of 2 in list list_2=list_of_numbers.copy() # copy() will copy the list_of_numbers to list_2 list_of_fruits.extend(list_of_animals) # extend() Merges two lists list_of_numbers.pop() # pop() removes last element of the list list_of_fruits.clear() # it will clear all the elements from list list_of_numbers.remove(1) # remove() removes given number list_of_numbers.insert(0,222) # insert(index,element) places element at your desired index print(dir(list_2)) # dir(list) gives all the operations related do list #-------slicing of List------------ list_of_players=['virat','rohit','hardik','shubham','jadeja'] print(list_of_players[0:5]) # Prints elemets from index 0 to index 4 print(list_of_players[::-1]) # Reverse of List print((list_of_players[0][::-1]).split()) # Reversing string of list and making that as list
2. List Comprehension
A concise way to create lists.
import list_op
#-----------list comprehension----------
# Normal
list_1=[]
for i in range(1,10):
list_1.append(i)
print(list_1)
# Comprehension
list_2=[i for i in range(1,6)] # One liner to create list
print(list_2)
list_odd=[i for i in range(1,10,2) ]
print(list_odd)
3. Dictionary in Python
Key-value pairs for efficient data retrieval.
dict_1={} #Empty dict
print(type(dict_1)) #<class 'dict'>
my_dict={'name':'ansar', #In dict Everything will be in Key and Value Pairs
'place':'bengaluru', # Keys Can Not Be REPEATED
'number':'2170'} # Keys Can Have same Value
print(my_dict['name']) # Method 1
print(my_dict.get('name')) # Method 2
#------Adding Elements----------
my_dict['hobby']='exercise'
print(my_dict)
#{'name': 'ansar', 'place': 'bengaluru', 'number': '2170', 'hobby': 'exercise'}
my_dict.update({'colour':'fair'})
print(my_dict)
#{'name': 'ansar', 'place': 'bengaluru', 'number': '2170', 'hobby': 'exercise', 'colour': 'fair'}
my_dict['name']='shaikansar'
print(my_dict)
#{'name': 'shaikansar', 'place': 'bengaluru', 'number': '2170', 'hobby': 'exercise', 'colour': 'fair'}
#---------------Delete Element---------------
my_dict.pop('colour')
print(my_dict)
#{'name': 'ansar', 'place': 'bengaluru', 'number': '2170', 'hobby': 'exercise'}
#----------Accessing Elements-------------
print(my_dict.keys())
#dict_keys(['name', 'place', 'number', 'hobby'])
print(my_dict.values())
#dict_values(['shaikansar', 'bengaluru', '2170', 'exercise'])
print(my_dict.items())
#dict_items([('name', 'shaikansar'), ('place', 'bengaluru'), ('number', '2170'), ('hobby', 'exercise')])
#-------------iteration--------------
for key in my_dict.keys():
print(key)
for value in my_dict.values():
print(value)
for key,value in my_dict.items():
print(key,value)
4. Tuples and Operations
Immutable sequences of elements.
test_tuple=1, #tuple is a sequence
print(type(test_tuple)) #<class 'tuple'>
test_tuple_1=(1,)
print(type(test_tuple_1)) #<class 'tuple'>
my_tuple=(1,2,3,4)
#my_tuple[1]=4
#TypeError: 'tuple' object does not support item assignment
print(my_tuple[0]) # my_tuple[1]=4
tuple_of_list=([1,2,3],90,4.5,'ansar')
tuple_of_list[0].append(22)
print(tuple_of_list)
#([1, 2, 3, 22], 90, 4.5, 'ansar')
#------- Slicing------------
print(tuple_of_list[0:3])
#([1, 2, 3, 22], 90, 4.5)
5. Set and Operations
Unordered collections of unique elements.
test_set=set() #Empty
print(type(test_set)) #<class 'set'>
set_of_fruits={'mango','apple','banana','orange','kiwi','mango','papaya'}
another_set_of_fruits={'pinapple','watermealon','lichi','apple','mango'}
print(set_of_fruits)# unordered & stores unique values
#{'orange', 'kiwi', 'apple', 'papaya', 'mango', 'banana'}
set_of_fruits.add('graphes')
print(set_of_fruits)
#{'banana', 'papaya', 'graphes', 'apple', 'orange', 'kiwi', 'mango'}
set_of_fruits.remove('banana')
print(set_of_fruits)
#{'mango', 'orange', 'papaya', 'apple', 'kiwi', 'graphes'}
6. Array and Initializing Using Class-Based Approach
Arrays implemented using classes.
import array
arr=array.array('i',[]) #empty
print(arr)
#-----Adding Elements--------
for i in range(1,6):
arr.append(i)
print(arr)
#-----Removing last Element------
arr.pop()
print(arr)
#-----Removing given indexed element-----
arr.pop(2)
print(arr)
7. Stack
A last-in, first-out (LIFO) data structure.
import array
class Stack:
def __init__(self):
self.my_array=array.array('i',[])
def is_empty(self):
if len(self.my_array):
return False
else:
return True
def push(self,element):
self.my_array.append(element)
def pop(self):
if self.is_empty():
print("stack is empty can't pop")
else:
self.my_array.pop()
if __name__=="__main__":
stack=Stack()
print(stack.my_array)
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.my_array)
stack.pop()
print(stack.my_array)
stack.pop()
print(stack.my_array)
stack.pop()
print(stack.my_array)
stack.pop()
8. Queue in Pytho
A first-in, first-out (FIFO) data structure.
from collections import deque
import array
class Queue:
def __init__(self):
self.my_queue=array.array('i',[])
def get_front(self):
print(len(self.my_queue)-1)
def enqueue(self,element):
self.my_queue.append(element)
def is_empty(self):
if len(self.my_queue):
return False
else:
return True
def dequeue(self):
if self.is_empty():
print("Queue is empty can't dequeue")
else:
self.my_queue.pop(0)
if __name__=="__main__":
queue=Queue()
print(queue.my_queue)
queue.get_front()
queue.enqueue(1)
print(queue.my_queue)
queue.get_front()
queue.enqueue(2)
print(queue.my_queue)
queue.get_front()
queue.enqueue(3)
print(queue.my_queue)
queue.dequeue()
print(queue.my_queue)
queue.dequeue()
queue.dequeue()
queue.dequeue()
9. LinkedList in Python
A collection of nodes, each pointing to the next one..
class Node:
def __init__(self,data):
self.data=data
self.nextval=None
class LinkedList:
def __init__(self):
self.head=None
def traverse(self):
current=self.head
while current is not None:
print(current.data)
current=current.nextval
if __name__=="__main__":
n1=Node(1)
n2=Node(2)
n3=Node(3)
#print(n1.data)
linkedlist=LinkedList()
linkedlist.head=n1
linkedlist.head.nextval=n2
n2.nextval=n3
n3.nextval=None
linkedlist.traverse()
10. Trees in Python
Hierarchical data structures.
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.data=data
def show(self):
if self.left:
self.left.show()
print(self.data)
if self.right:
self.right.show()
root=Node(100)
r_left=Node(99)
r_right=Node(101)
root.left=r_left
root.right=r_right
root.show()
Conclusion
You've now gained a brief understanding of Python installation and explored key data structures. To access the code examples, visit my GitHub repository: PythonDSA. Happy coding!