<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Adarsh Rawat</title>
    <description>The latest articles on DEV Community by Adarsh Rawat (@adarshrawat7400).</description>
    <link>https://dev.to/adarshrawat7400</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F747196%2F7abe33ba-237a-4f52-bccf-a74d6d174c6b.png</url>
      <title>DEV Community: Adarsh Rawat</title>
      <link>https://dev.to/adarshrawat7400</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/adarshrawat7400"/>
    <language>en</language>
    <item>
      <title>How Call by Value and Call by Reference Work in Python?</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Mon, 15 Nov 2021 15:12:49 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/how-call-by-value-and-call-by-reference-work-in-python-am2</link>
      <guid>https://dev.to/adarshrawat7400/how-call-by-value-and-call-by-reference-work-in-python-am2</guid>
      <description>&lt;p&gt;In this &lt;em&gt;Article&lt;/em&gt; we're going to understand how call by value and call by reference work in &lt;em&gt;python&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Let's first understand what is call by value and call by reference&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Call By Value :-&lt;/strong&gt;
In Call by value the value(copy) of the parameters passed as &lt;em&gt;formal argument&lt;/em&gt; ina &lt;em&gt;function&lt;/em&gt; instead of the variable itself, so in this case if any modification applied to the function parameters it will not be &lt;em&gt;reflected&lt;/em&gt; on the actual variable.**&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;let's take example in C programming langauge to better understand call by value and call by reference&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Example :-&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void call_by_value(int a , int b){
    a = 44;
    b = 55;
}

int main() {
    int a  = 1;
    int b = 2;
    printf("value of a and b before function call :- %d and %d",a,b);
    call_by_value(a, b);
    printf("\nvalue of a and b after function call :- %d and %d",a,b);
    return 0;
}
Output :-
value of a and b before function call :- 1 and 2
value of a and b after function call :- 1 and 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above example the value of varible a and b not modified because a copy of a,b passed instead of their addresses&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Call By Reference :-&lt;/strong&gt;
In Call By Reference, the address(actual varible) of the variable is passed into the function call as the actual parameter.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, if any modification applied to the function parameters it will  be &lt;em&gt;reflected&lt;/em&gt; on the actual variable.**&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Example :-&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void call_by_reference(int *a , int *b){
    *a = 44;
    *b = 55;
}

int main() {
    int a  = 1;
    int b = 2;
    printf("value of a and b before function call :- %d and %d",a,b);
    call_by_reference(&amp;amp;a, &amp;amp;b);
    printf("\nvalue of a and b after function call :- %d and %d",a,b);
    return 0;
}
Output :-
value of a and b before function call :- 1 and 2
value of a and b after function call :- 44 and 55
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above example the address of varible a and b  using &lt;strong&gt;&amp;amp;&lt;/strong&gt; followed by variable name , where  in function defination&lt;br&gt;
 &lt;strong&gt;*&lt;/strong&gt; followed parameter known as &lt;em&gt;pointer variable&lt;/em&gt; which used&lt;br&gt;
to storing addresses, because of this values in varible &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; is modified.&lt;/p&gt;

&lt;p&gt;Now we have seen what is &lt;em&gt;call by value and call by reference&lt;/em&gt; with example&lt;/p&gt;

&lt;p&gt;But, &lt;em&gt;Python&lt;/em&gt; programming language uses the mechanism of the &lt;strong&gt;call-by-object&lt;/strong&gt; and also &lt;strong&gt;call by object reference&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Each object whenever it is instantiated ,it is assigned  unique &lt;strong&gt;id&lt;/strong&gt;  and its type if defined at &lt;em&gt;runtime&lt;/em&gt; and &lt;em&gt;id(object)&lt;/em&gt; returns a unique identity (integer value) of that object.&lt;/p&gt;

&lt;p&gt;to move further into the topic first we have to understand &lt;em&gt;mutable&lt;/em&gt; object and &lt;em&gt;immutable&lt;/em&gt; object in python.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Mutable Objects&lt;/strong&gt;&lt;br&gt;
Datatypes that can be modified or if there state can be changed those objects are known as &lt;em&gt;Mutable&lt;/em&gt; datatype&lt;br&gt;
like &lt;strong&gt;(list, dictionaries, set)&lt;/strong&gt; .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Immutable Objects&lt;/strong&gt;&lt;br&gt;
Datatypes that cannot be modified or if there state cannot be changed those objects are known as &lt;em&gt;Immutable&lt;/em&gt; datatype like **(int, float, bool, string, unicode, tuple). &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;So when &lt;em&gt;Mutable&lt;/em&gt; objects are passed to the &lt;em&gt;function&lt;/em&gt; call then it is treated as **call by value&lt;/strong&gt;.**&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;And When &lt;em&gt;Immutable&lt;/em&gt; objects  are passed to the &lt;em&gt;function&lt;/em&gt; call  and there value is modified then it is treated as **call by reference&lt;/strong&gt;.**&lt;/p&gt;

&lt;p&gt;For the  sake of simplicity we're going to use the word call by value and call by reference instead of (call by object) and (call by object reference) respectivly.&lt;/p&gt;

&lt;p&gt;let's take examples for call by reference and call by value&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example :- Call by reference (with Immutable objects (int, float, bool, string) and no object state modified) in python&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;num1  = 43
num2 = 12.44
num3 = False
name = 'hello'
print("Id in main function scope")
print(f"id of num1  = {id(num1)}")
print(f"id of num2  = {id(num2)}")
print(f"id of num2  = {id(num3)}")
print(f"id of name = {id(name)}")


def call_by_reference(num1,num2,num3,name):
  print("\nId within function")
  print(f"id of num1  = {id(num1)}")
  print(f"id of num2  = {id(num2)}")
  print(f"id of num2  = {id(num3)}")
  print(f"id of name = {id(name)}")


call_by_reference(num1,num2,num3,name)

Output :-
Id in main function scope
id of num1  = 94157957099328
id of num2  = 140438713493200
id of num2  = 94157956423968
id of name = 140438848940272

Id within function
id of num1  = 94157957099328
id of num2  = 140438713493200
id of num2  = 94157956423968
id of name = 140438848940272

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we can see that the id's the objects &lt;em&gt;(num1, num2, num3)&lt;/em&gt; has not change becuase have not applied modification to those objects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example :- Call by reference (with Mutable objects (list ,dict) and object state modified) in python&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = ['ram', 'shyam', 'bharat']
d =  {'bob':21,'max':22}
print("Id in main function scope")
print(f"id of names list  = {id(names)}")
print(f"id of d dict  = {id(d)}")

def call_by_reference(name, d):
  print("Id within function")

  d['sam'] = 12
  names.append('john')

  print("\nModified Objects id :-")
  print(f"id of names list  = {id(names)}")
  print(f"id of d dict  = {id(d)}")

call_by_reference(names, d)
print("Modfied list and dict")
print(f"names =   {names}")
print(f"dict = {d}")

Output :-

Id in main function scope
id of names list  = 140439297460096
id of d dict  = 140438712179600
Id within function

Modified Objects id :-
id of names list  = 140439297460096
id of d dict  = 140438712179600
Modfied list and dict
names =   ['ram', 'shyam', 'bharat', 'john']
dict = {'bob': 21, 'max': 22, 'sam': 12}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can see even after modifying the objects state the &lt;em&gt;id's&lt;/em&gt; of the object remains unchanged because the objects datatype are &lt;em&gt;mutable&lt;/em&gt; objects here by ,even if the object state is modified&lt;br&gt;
it is treated as call by reference(call by object reference).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;==============================================&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example :- Call by Value (with Immutable objects (int, float, bool, string) and object state modified) in python&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;num1  = 43
num2 = 12.44
num3 = False
name = 'hello'
print("Id in main function scope")
print(f"id of num1  = {id(num1)}")
print(f"id of num2  = {id(num2)}")
print(f"id of num2  = {id(num3)}")
print(f"id of name = {id(name)}")


def call_by_value(num1,num2,num3,name):
  print("\nId within function")
  num1 = 1
  num2 = 2
  num3 = 3
  name = 'sam'
  print("Modified Objects id")

  print(f"id of num1  = {id(num1)}")
  print(f"id of num2  = {id(num2)}")
  print(f"id of num2  = {id(num3)}")
  print(f"id of name = {id(name)}")


call_by_value(num1,num2,num3,name)
print("\Unmodified int, float, bool, string objects value in global scope")
print(f'num1 = {num1}')
print(f'num2 = {num2}')
print(f'num3 = {num3}')

Output :-
Id in main function scope
id of num1  = 94157957099328
id of num2  = 140438713494320
id of num2  = 94157956423968
id of name = 140438848940272

Id within function
Modified Objects id
id of num1  = 94157957097984
id of num2  = 94157957098016
id of num2  = 94157957098048
id of name = 140438713157936

Unmodified int, float, bool, string objects value in global scope
num1 = 43
num2 = 12.44
num3 = False

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we can see that after modifying the &lt;em&gt;Immuatable&lt;/em&gt; objects the object &lt;em&gt;id's&lt;/em&gt; were diffrent , this is because we cannot modify the value of &lt;em&gt;Immutables&lt;/em&gt; and because of this new 3 objects named (&lt;em&gt;num1, num2, num3, name&lt;/em&gt;) where created in the function &lt;em&gt;local&lt;/em&gt; scope after the function call we have also print the value to verify the  objects in the &lt;em&gt;global&lt;/em&gt; scope remain unchanged.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example :- Call by Value (with Immutable objects (tuple) and object state modified) in python&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = ('ram', 'shyam', 'bharat')
print("Id in main function scope")
print(f"id of names tuple  = {id(names)}")

def call_by_value(name, d):
  print("Id within function")
  names = ('ram','shyam','bharat','john')
  print(f"modified object value \n{names}")
  print("\nModified Objects id :-")
  print(f"id of names tuple  = {id(names)}")

call_by_value(names, d)
print("\nUnchanged tuple object in global scope")
print(f"names = {names}")

Output :-
Id in main function scope
id of names tuple  = 140438712974144
Id within function
modified object value 
('ram', 'shyam', 'bharat', 'john')

Modified Objects id :-
id of names tuple  = 140438712255888

Unchanged tuple object in global scope
names = ('ram', 'shyam', 'bharat')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we can have assigned a new &lt;em&gt;tuple&lt;/em&gt; with same elements + one more element because (&lt;em&gt;tuple&lt;/em&gt; datatype does not support  any &lt;em&gt;add&lt;/em&gt; method) andchecked the object &lt;em&gt;id&lt;/em&gt; which is diffrent because a new object gets created and also the global object remain unchanged because of it's &lt;em&gt;Immutable&lt;/em&gt; nature.&lt;/p&gt;

&lt;p&gt;With this example we have come to an end&lt;br&gt;
hope you all have understood the topics&lt;br&gt;
covered in this article.&lt;/p&gt;

&lt;p&gt;:-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>File handling in Python</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Sat, 13 Nov 2021 12:58:53 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/learn-file-handling-in-python-2nhk</link>
      <guid>https://dev.to/adarshrawat7400/learn-file-handling-in-python-2nhk</guid>
      <description>&lt;p&gt;In  this Article we going to learn following topics :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Read data from a &lt;em&gt;file&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Write data to a &lt;em&gt;file&lt;/em&gt; .&lt;/li&gt;
&lt;li&gt;Append Data to a &lt;em&gt;file&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Delete a &lt;em&gt;file&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We're going to cover each of the above point with meaningful examples.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;python&lt;/em&gt; &lt;em&gt;open()&lt;/em&gt; function is used to perform various &lt;em&gt;operations&lt;/em&gt; on files, operation such as&lt;br&gt;
(read,write,append,delete).&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;open()&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Syntax&lt;/strong&gt; :- &lt;em&gt;open(filename, mode)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;open()&lt;/em&gt; function takes two argument &lt;em&gt;filename&lt;/em&gt; and &lt;em&gt;mode&lt;/em&gt;, and return a &lt;em&gt;TextIOWrapper&lt;/em&gt; class object.&lt;/p&gt;

&lt;p&gt;There are four different modes available :-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;r&lt;/strong&gt; mode is the default when no mode passed, used to read file, it throws &lt;em&gt;FileNotFoundError&lt;/em&gt; if the file passed in first argument does not exist.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;w&lt;/strong&gt; mode is write data into a file, if data exist in the &lt;em&gt;file&lt;/em&gt; it removes that data then, start writing the data into the file , if the &lt;em&gt;filename&lt;/em&gt; passed does not exist,it creates a new file.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;a&lt;/strong&gt; mode write data to existing &lt;em&gt;file&lt;/em&gt;, creates a file if it does not exist.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;delete  file with specified &lt;em&gt;filename&lt;/em&gt; using &lt;em&gt;os&lt;/em&gt; module ,if the file does not exist it throws &lt;em&gt;FileExistsError&lt;/em&gt; error.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other then that , you are specify the mode in which file will we handled.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;t&lt;/strong&gt; in Text mode.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;b&lt;/strong&gt; in Binary mode.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For Example :-&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;file1 = open("file.txt",'wb') # means write in binary mode
file2 = open("file.txt",'wt') # means write in text mode
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Default mode is &lt;em&gt;Text mode&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;After doing all the operation on file use can call &lt;em&gt;file.close()&lt;/em&gt; method to close a file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Throughout the examples we're going to us the below file&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;filename :- students.txt
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Name : Ram Kumar
Age  : 13
City : Ajmir

Name : Alice Pen
Age  : 12
City : Boston

Name : Marcus Lee
Age  : 15
City : Tokyo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Read data from file&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;file = open("students.txt",'r')

for line in file:
    print(line,end="")

file.close()

Output :-
Name : Ram Kumar
Age  : 13
City : Ajmir

Name : Alice Pen
Age  : 12
City : Boston

Name : Marcus Lee
Age  : 15
City : Tokyo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In the above code , used &lt;em&gt;for&lt;/em&gt; to the read one line at a time and print it, we're added &lt;em&gt;end=""&lt;/em&gt; in print statement because , in file , a line ends with &lt;em&gt;\n&lt;/em&gt; implicitly.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Write data to file&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;file = open("students_2.txt",'w')
student_info = { 
    "Name" : "Mike Javen",
    'Age' : 15,
    'City' : 'Minisoda'
}

for field,data in student_info.items():
    file.write(f"{field} : {data}  \n")

file.close()

students_2.txt file content :-

Name : Mike Javen  
Age : 15  
City : Minisoda  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here, we have used &lt;em&gt;write()&lt;/em&gt; function , new file &lt;em&gt;students_2.txt&lt;/em&gt; gets created, because it does not exist in the first place ,and we have added a student info to that file, we not added this student data to &lt;em&gt;students.txt&lt;/em&gt; file because in &lt;em&gt;w&lt;/em&gt; mode the data in the file first gets deleted and then writing starts.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Append data to file&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;file = open("students.txt",'a')
students_info = [ { 
    "Name" : "John Lenon",
    'Age' : 14,
    'City' : 'Navi Mumbai'    
 }, 
 { 
    "Name" : "Sam Dune",
    'Age' : 11,
    'City' : 'Boston'    
 }
]

for student_info in students_info:
    file.write("\n")
    for field,data in student_info.items():
        file.write(f"{field} : {data}  \n")

file.close()

Students.txt file.content :-

Name : Ram Kumar
Age  : 13
City : Ajmir

Name : Alice Pen
Age  : 12
City : Boston

Name : Marcus Lee
Age  : 15
City : Tokyo

Name : John Lenon  
Age : 14  
City : Navi Mumbai  

Name : Sam Dune  
Age : 11  
City : Boston  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In the above code we added 2 new students details in &lt;em&gt;students.txt&lt;/em&gt; file using 'a' append mode,&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Delete a file&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os

filename = 'students_2.txt'
os.remove(filename)

print(f"successfully deleted file {filename}")

Output :-
successfully deleted file students_2.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The above example is fairly simple one in which we import python &lt;em&gt;os&lt;/em&gt; module to delete the file in the current directory i.e., &lt;em&gt;students_2.txt&lt;/em&gt; if the file does not exist in the diretory it throws error &lt;em&gt;FileNotFoundError&lt;/em&gt; error.&lt;/p&gt;

&lt;p&gt;With this we have seen all 4 &lt;em&gt;opearation&lt;/em&gt; on a file, I'd like to mention another way in which we can perform same &lt;em&gt;opeartions&lt;/em&gt; we talked about, where we does not have to explicitly &lt;em&gt;close()&lt;/em&gt; the file working with the file.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Alternative&lt;/strong&gt; way
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open("students.txt",'r') as file:
    for line in file:
        print(line, end="")

Output :-
Name : Ram Kumar
Age  : 13
City : Ajmir

Name : Alice Pen
Age  : 12
City : Boston

Name : Marcus Lee
Age  : 15
City : Tokyo

Name : John Lenon
Age : 14
City : Navi Mumbai

Name : Sam Dune
Age : 11
City : Boston

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here, we have used &lt;em&gt;with&lt;/em&gt; keyword and &lt;em&gt;as&lt;/em&gt; alias as soon as the with block ends, the file gets closed implicitly, we can use the same &lt;em&gt;syntax&lt;/em&gt; with other modes&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Writing file in Binary Mode&lt;/strong&gt;
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;file = open("new_students.txt",'wb')
students_info = b'''
    "Name" : "Sam Dune",
    'Age' : 11,
    'City' : 'Boston'
     }
     '''
file.write(students_info)
file.close()

Output :-

    "Name" : "Sam Dune",
    'Age' : 11,
    'City' : 'Boston'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here we have write bytes to a files&lt;/p&gt;

&lt;p&gt;Before Finishing this &lt;em&gt;Article&lt;/em&gt; I'd like to cover some useful examples of file processing.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Example&lt;/strong&gt; :-
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Reading the entire file content and storing it list for further processing&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# file content :-
#my name is john levi and i
#live in boston and study in
#xyz univeristy doing majors
#in computer science.

person_info = [line for line in open('info.txt')]

for line in person_info:
    print(line,end="")

Output :-
my name is john levi and i
live in boston and study in
xyz univeristy doing majors
in computer science.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here we fetched the content of entire file using &lt;em&gt;list compreshension&lt;/em&gt; in just single line remember this file could be of 1000 of line for some operation we have to read file again and again, in this way we can just used the file content stored in the list.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Example&lt;/strong&gt; :-
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Reading the file content and storing it content in some &lt;em&gt;collection&lt;/em&gt; like dictionaries datatype&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# File Content :-
# Ram Kumar , 12 , Indore
# Shayam Kumar, 13 , Mumbai
# Ajay Kumar, 11 , Delhi
# Harris javen, 15 , New Jersey


students_info = []
for line in open("info.txt"):
    name, age, city = line.split(',')
    student = {
        "Name" : name.strip(),
        "Age" : age.strip(),
        "City" : city.strip()
    }
    students_info.append(student)

print("Content tetched from file and stored in dictionary\n")
for student in students_info:
    print(student)

Output :-

Content tetched from file and stored in dictionary

{'Name': 'Ram Kumar', 'Age': '12', 'City': 'Indore'}
{'Name': 'Shayam Kumar', 'Age': '13', 'City': 'Mumbai'}
{'Name': 'Ajay Kumar', 'Age': '11', 'City': 'Delhi'}
{'Name': 'Harris javen', 'Age': '15', 'City': 'New Jersey'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;with this example we have come to an end hope you all have understood the topics covered in this article.&lt;/p&gt;

&lt;p&gt;:-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Learn Generators in Python with (Examples)</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Fri, 12 Nov 2021 17:47:28 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/learn-generators-in-python-with-examples-ad3</link>
      <guid>https://dev.to/adarshrawat7400/learn-generators-in-python-with-examples-ad3</guid>
      <description>&lt;p&gt;In this Article we will going to look following topics&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Understanding &lt;strong&gt;Generators&lt;/strong&gt; in Python,with Examples&lt;/li&gt;
&lt;li&gt;Also how to construct our own &lt;em&gt;Generator&lt;/em&gt; function &lt;/li&gt;
&lt;li&gt;Advantages of using &lt;em&gt;Generator&lt;/em&gt; function instead of &lt;em&gt;regular&lt;/em&gt; function in some cases&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Generators :-
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Generator&lt;/em&gt; are the special function which returns an traversal object which used to iterate over a &lt;em&gt;collection of values&lt;/em&gt;, it is also used to create &lt;em&gt;iterators&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is can also be expressed in a way which is simiar to &lt;em&gt;list compreshension&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Just like iterator &lt;em&gt;next()&lt;/em&gt; method we can also iterate over &lt;em&gt;generator&lt;/em&gt; using &lt;em&gt;generator.next()&lt;/em&gt; to iterate over the &lt;em&gt;generator&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Creating a Geneartor :-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It is simple to create a &lt;em&gt;Generator&lt;/em&gt; function if you have worked with regular function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In &lt;em&gt;Generator&lt;/em&gt; function instead of using &lt;em&gt;return&lt;/em&gt; statement we use yield statement.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A function with &lt;em&gt;yield&lt;/em&gt; keyword in it is called a &lt;em&gt;Generator&lt;/em&gt; function&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;generator&lt;/em&gt; throws &lt;em&gt;StopIteration&lt;/em&gt; Exception when &lt;em&gt;next()&lt;/em&gt; method called on the last &lt;em&gt;element&lt;/em&gt; in the genearator,&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We have to &lt;em&gt;explicitly&lt;/em&gt; handle &lt;em&gt;StopIteration&lt;/em&gt; Exception when&lt;br&gt;
  using &lt;em&gt;next()&lt;/em&gt; method with &lt;em&gt;generator&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's use take an example to understand the above points :-&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Normal function
def func():
    letters = ['a', 'b', 'c', 'd', 'e']
    for c in letters:
        return c

# Generator function
def generator_func():
    letters = ['a', 'b', 'c', 'd', 'e']
    for c in letters:
        yield c

print("Normal function :-")
print(func())

print("\nGenerator function :-")
print(generator_func())

print("\nIterating over generator using next() method")
gen = generator_func()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))

Output :-

Normal function :-
a

Generator function :-
&amp;lt;generator object generator_func at 0x00000180318F9A10&amp;gt;

Iterating over generator using next() method
a
b
c
d
e
Traceback (most recent call last):
  File "C:\Users\adars\Desktop\test.py", line 26, in &amp;lt;module&amp;gt;
    print(next(gen))
StopIteration   
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now , you can se a normal function return the value which we have return but , &lt;em&gt;Generator&lt;/em&gt; function return &lt;em&gt;generator&lt;/em&gt; object (traversal object)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;we can &lt;em&gt;iterate&lt;/em&gt; over the &lt;em&gt;generator object&lt;/em&gt;, let's see how?&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for i in generator_func():
    print(i)

Output :-
a
b
c
d
e
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we iterated over the generator object in the above code,&lt;/p&gt;

&lt;p&gt;Now you're probably thinking what is the &lt;strong&gt;difference&lt;/strong&gt; between :-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;function with return&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;function with yield&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;function with &lt;em&gt;return&lt;/em&gt; statement&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;when the &lt;em&gt;return&lt;/em&gt; statement called , the function terminates it execution
and return the value, removing the function from the &lt;em&gt;call stack&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;function with &lt;em&gt;yield&lt;/em&gt; statement&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;yield&lt;/em&gt; controls the flow of &lt;em&gt;Genearator&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;yield&lt;/em&gt; pauses the function state and  &lt;em&gt;yielded&lt;/em&gt; value to the caller&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;yield&lt;/em&gt; resume the function execution on &lt;em&gt;yield&lt;/em&gt; statement successfully&lt;/li&gt;
&lt;li&gt;there can be multiple &lt;em&gt;yield&lt;/em&gt; statement per &lt;em&gt;Generator&lt;/em&gt; function&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Generator with multiple &lt;em&gt;yield&lt;/em&gt; statements
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def generator_func2():
    numbers = [1, 2, '3', '4', 5, 6, '7', 8, 9, '10']
    for num in numbers:
        if type(num) == int:
            yield f"{num} is an integer form"
        elif type(num) == str:
            yield f"{num} is an string form"



for i in generator_func2():
    print(i)


Output :-
1 is an integer form
2 is an integer form
3 is an string form
4 is an string form
5 is an integer form
6 is an integer form
7 is an string form
8 is an integer form
9 is an integer form
10 is an string form
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we created a &lt;em&gt;Generator&lt;/em&gt; function which uses&lt;br&gt;
multiple &lt;em&gt;yield&lt;/em&gt; statments&lt;/p&gt;

&lt;h4&gt;
  
  
  Creating &lt;em&gt;Generator&lt;/em&gt; in one line
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Just like &lt;em&gt;list comprehension&lt;/em&gt; , we can create &lt;em&gt;Generators&lt;/em&gt; in single line&lt;/li&gt;
&lt;li&gt;Instead of &lt;em&gt;[ ]&lt;/em&gt; brackets ,we use &lt;em&gt;( )&lt;/em&gt; to create a &lt;em&gt;generator&lt;/em&gt; function&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers_generator = (i for i in range(10))
print(type(numbers_generator))

for num in numbers_generator:
    print(num)

Output :-
0
1
2
3
4
5
6
7
8
9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we have created a &lt;em&gt;Generator&lt;/em&gt; function  which belong to &lt;em&gt;generator&lt;/em&gt; class, in a way similar to &lt;em&gt;list comprehension&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;let's take some more example of &lt;em&gt;generators&lt;/em&gt; function&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If your fimilar with &lt;em&gt;range()&lt;/em&gt; function in python , we will going to implement our own &lt;em&gt;range()&lt;/em&gt; function with the help of &lt;em&gt;generators&lt;/em&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def range(start = 0,stop = 0,stepby = 1):
    yield start
    while(start &amp;lt; stop):
        yield start+stepby
        start += stepby

print("range() function implementation :-")
print(type(range(0,10)))


for i in range(0,10):
    print(i)

print("\n---------\n")

for i in range(0,10,2):
    print(i)

Output :-
range() function implementation :-
&amp;lt;class 'generator'&amp;gt;
0
1
2
3
4
5
6
7
8
9
10

---------

0
2
4
6
8
10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have created a simple &lt;em&gt;implementation&lt;/em&gt; of &lt;em&gt;range()&lt;/em&gt; function &lt;br&gt;
using &lt;em&gt;generators&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;We will going to write two implementation of  *fibonacci sequence&lt;/em&gt; using &lt;em&gt;generators&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def fibo_seq_generator(n):

    # Initialize first two Fibonacci Numbers 
    a, b = 0, 1

    # One by one yield next Fibonacci Number
    while a &amp;lt; n:
        yield a
        a, b = b, a + b

print("Fibonacci sequence using generator :- ")
for i in fibo_seq_generator(20):
    print(i)

Output :- 
Fibonacci sequence using generator :-
0
1
1
2
3
5
8
13
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have covered many examples of &lt;em&gt;generators&lt;/em&gt; and&lt;br&gt;
learned how to create &lt;em&gt;generators&lt;/em&gt;, now we're going to see &lt;br&gt;
the advantages of generator :-&lt;/p&gt;

&lt;h3&gt;
  
  
  Advantages of &lt;strong&gt;Genearators&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It is Easy to Implement a &lt;em&gt;generators&lt;/em&gt; relatively compared to&lt;br&gt;
an iterator , which requires you to implement &lt;strong&gt;&lt;em&gt;iter&lt;/em&gt;_()&lt;/strong&gt; and&lt;br&gt;
&lt;strong&gt;&lt;strong&gt;next&lt;/strong&gt;()&lt;/strong&gt; function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Genearators&lt;/em&gt; are memory efficient when working with large&lt;br&gt;
sequence of numbers because &lt;em&gt;yield&lt;/em&gt; statement give value to&lt;br&gt;
the caller function whenever &lt;em&gt;yield&lt;/em&gt; line gets executed ,&lt;br&gt;
So it doesn't have to store the entire sequence in the memory,&lt;br&gt;
whereas in case of normal function ,it stores the sequence&lt;br&gt;
somewhere in memory(in call stack) before returning the result.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;With &lt;em&gt;Generators&lt;/em&gt; we can generate infinite sequence of numbers without needing to worry about computer memory usage.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Generators&lt;/em&gt; used in &lt;strong&gt;Data Pipeline&lt;/strong&gt; which provides the facility to process large datasets or stream of data without using extra computer memory.   &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;with this we have successfully completed&lt;br&gt;
&lt;em&gt;Generators in Python with (Examples) Article&lt;/em&gt; &lt;br&gt;
hope you all have understand the topics&lt;br&gt;
covered in this Article.&lt;/p&gt;

&lt;p&gt;:-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
      <category>generators</category>
    </item>
    <item>
      <title>Object Serialization and Deserialzation in Python</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Fri, 12 Nov 2021 10:48:13 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/serializing-and-de-serializing-in-python-30g0</link>
      <guid>https://dev.to/adarshrawat7400/serializing-and-de-serializing-in-python-30g0</guid>
      <description>&lt;p&gt;In this Article we're going to see :-&lt;/p&gt;

&lt;p&gt;&lt;em&gt;serializing object *(a process called serialization)&lt;/em&gt;&lt;br&gt;
&lt;em&gt;de-serializing object *(a process called de-serialization)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;let's start with the definations :-&lt;/p&gt;
&lt;h3&gt;
  
  
  Serialization :-
&lt;/h3&gt;

&lt;p&gt;Serialization is the process of converting data structures or object state into a format that can be stored or saved in memory for latter use, that format in which the object state saved will follow some rules which will help in &lt;em&gt;de-serializing&lt;/em&gt; the object later.&lt;/p&gt;
&lt;h3&gt;
  
  
  De-serialization :-
&lt;/h3&gt;

&lt;p&gt;De-serialization is just opposite of &lt;em&gt;serialization&lt;/em&gt; in De-serialization ,we get the object state back to recreate the original object from the serialized format.&lt;/p&gt;

&lt;p&gt;Now that we have understand defination of &lt;em&gt;serialization and de-serialization&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;let's see some place where they are very helpful&lt;/strong&gt; :-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;While sending data over the &lt;em&gt;internet&lt;/em&gt; the data is transfered mostly in &lt;em&gt;Json&lt;/em&gt; form (JSON is a format that encodes objects in a string and deserialization it (convert string -&amp;gt; object))&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Hugh Machine Learning Model that are trained on hugh amount of data ,need to stored in some form for later use ,we cannot re-train them again and again , that is where serialization help&lt;br&gt;
to  store &lt;em&gt;ML model&lt;/em&gt; state.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Big Data&lt;/em&gt; system uses &lt;em&gt;serialization and deseralization&lt;/em&gt; to store large amount of data.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;we have seen only few applications, &lt;em&gt;serialization&lt;/em&gt; and &lt;em&gt;deserialization&lt;/em&gt; are pretty much applied whererever there is need to store data in some form to use it for later use.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;Now we going to look how to do &lt;em&gt;Serialzation and Deserializatiom&lt;/em&gt; in Python&lt;/strong&gt;
&lt;/h4&gt;
&lt;h3&gt;
  
  
  &lt;em&gt;Pickle&lt;/em&gt; :-
&lt;/h3&gt;

&lt;p&gt;Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. &lt;br&gt;
Pickling is a way to convert a python object (list, dict, etc.) into a character stream&lt;br&gt;
It saves the find the &lt;em&gt;.pkl&lt;/em&gt; format&lt;/p&gt;

&lt;p&gt;methods available :-&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;dump() − The dump() method serializes to an open file (file-like object).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;dumps() − Serializes to a string&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;load() − Deserializes from an open-like object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;loads() − Deserializes from a string.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Serializing the object&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pickle
class Student:
  def __init__(self,firstname,lastname,age,standard):
    self.firstname = firstname
    self.lastname = lastname
    self.age = age
    self.standard = standard

  def showinfo(self):
    print(f"Firstname :- {self.firstname}")
    print(f"Lastname :- {self.lastname}")
    print(f"Age :- {self.age}")
    print(f"Standarad :- {self.standard}")


student1 = Student("Adarsh","Raven",21,"12th")
student2 = Student("Ankit",'Raven',24,'11th')


# Student Info
print("Student1 :- ")
student1.showinfo()


print("\nStudent2 :- ")
student2.showinfo()

# Serializing object
picked_student1 = pickle.dumps(student1)
picked_student2 = pickle.dumps(student2)

# Object stored in Byte steam
print("serialized student",picked_student1)


Output :-

Student1 :- 
Firstname :- Adarsh
Lastname :- Raven
Age :- 21
Standarad :- 12th

Student2 :- 
Firstname :- Ankit
Lastname :- Raven
Age :- 24
Standarad :- 11th
serialized student b'\x80\x03c__main__\nStudent\nq\x00)\x81q\x01}q\x02(X\t\x00\x00\x00firstnameq\x03X\x06\x00\x00\x00Adarshq\x04X\x08\x00\x00\x00lastnameq\x05X\x05\x00\x00\x00Ravenq\x06X\x03\x00\x00\x00ageq\x07K\x15X\x08\x00\x00\x00standardq\x08X\x04\x00\x00\x0012thq\tub.'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Deserializing the same object&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;orignal_student1 = pickle.loads(picked_student1)
orignal_student2 = pickle.loads(picked_student2)

print("\n\nAfter Getting object back from the saved state :- \n")
print("Student1 :- ")
orignal_student1.showinfo()

print("\nStudent2 :- ")
orignal_student2.showinfo()

Output :-

After Getting object back from the saved state :- 

Student1 :- 
Firstname :- Adarsh
Lastname :- Raven
Age :- 21
Standarad :- 12th

Student2 :- 
Firstname :- Ankit
Lastname :- Raven
Age :- 24
Standarad :- 11th
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;there are also other ways available to do the same task &lt;br&gt;
we have covered in the above example, it will mention resources to those if you're intrested :-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://pypi.org/project/joblib/"&gt;joblib&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/library/json.html"&gt;json&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;:-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Most Used Built-in functions in Python in</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Thu, 11 Nov 2021 17:27:15 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/most-used-built-in-functions-in-python-dn2</link>
      <guid>https://dev.to/adarshrawat7400/most-used-built-in-functions-in-python-dn2</guid>
      <description>&lt;p&gt;In this article we will going to look some very useful built-in functions that will always come handly in your python journey,&lt;br&gt;
these functions will save you writing extra lines of code,&lt;/p&gt;

&lt;p&gt;We will going to understand the defination and look some useful use-cases for each built-in function.&lt;/p&gt;

&lt;p&gt;We will going to go through the following built-in functions :-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;map()&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;filter()&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;reduce()&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;zip()&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;enumerate()&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;all()&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;any()&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  1. &lt;em&gt;map()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;map() is a built-in Python function that takes in two or more arguments: a function and one or more iterables, in the form:&lt;br&gt;
&lt;strong&gt;Syntax :- *map(callable, iterable)&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;map() returns an &lt;strong&gt;iterator&lt;/strong&gt; - that is, map() returns a special object that yields one result at a time as needed.&lt;br&gt;
if you're not fimiliar with &lt;em&gt;iterator&lt;/em&gt; :-&lt;br&gt;
refer to this post :- &lt;a href="https://dev.to/adarshrawat7400/what-is-iterableiterator-in-python-3325"&gt;iterator,iterable in python&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;for n size of input , it will return n size output&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's see some example of &lt;em&gt;map()&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Task :- convert list of string integer to to int&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Example:-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst_of_str_ints = ['1','2','3','4','5','6','7','8','9','10']
print("list of str ints :- ",lst_of_str_ints)

lst_of_ints = list(map(int, lst_of_str_ints))
print("list of ints :- ",lst_of_ints)

Output :-
list of str ints :-  ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
list of ints :-  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;we passed &lt;em&gt;int&lt;/em&gt; object as first argument in the map function, second argument is the &lt;em&gt;list_of_str_int&lt;/em&gt;, in this example&lt;br&gt;
the iterator iterate each element at a time and map it to the corresponding callable argument &lt;em&gt;int()&lt;/em&gt; passed as first argument,&lt;br&gt;
then after iterating over all the elements, the &lt;em&gt;map()&lt;/em&gt; function returns  a &lt;em&gt;map&lt;/em&gt; object will can then be &lt;em&gt;casted&lt;/em&gt; to iterable like &lt;br&gt;
&lt;em&gt;(list,tuple,set)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;we can perform the same task using &lt;em&gt;lambda function&lt;/em&gt;:-&lt;/p&gt;
&lt;h3&gt;
  
  
  Example:-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst_of_str_ints = ['1','2','3','4','5','6','7','8','9','10']
print("list of str ints :- ",lst_of_str_ints)

lst_of_ints = list(map(lambda x:int(x), lst_of_str_ints))
print("list of ints :- ",lst_of_ints)

Output :-
list of str ints :-  ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
list of ints :-  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Task :- we will convert temprature from celsius to fahrenheit&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;temps_in_celsius = [0, 22.5, 40, 100]
print("temprature in celsius :-",temps_in_celsius)

temps_in_fahrenheit = list(map(lambda celsius : (9/5)*celsius + 32, temps_in_celsius))
print("temprature in fahrenheit :-",temps_in_fahrenheit)

Output :-
temprature in celsius :- [0, 22.5, 40, 100]
temprature in fahrenheit :- [32.0, 72.5, 104.0, 212.0]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we converted &lt;em&gt;list of temperature in celsius&lt;/em&gt; to "temprature in fahrenheit"&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Task :- capitalize each name in a list to uppercase&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = ['Ram','Shyam','Abhiansh','Raven','Marcus']
print("Original list :-",names)

upper_cased_names = list(map(lambda x : x.upper(), names))
print("Upper case name :-",upper_cased_names)

Output :-
Original list :- ['Ram', 'Shyam', 'Abhiansh', 'Raven', 'Marcus']
Upper case name :- ['RAM', 'SHYAM', 'ABHIANSH', 'RAVEN', 'MARCUS']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. &lt;em&gt;filter()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;filter(function, iterable)( offers a efficient way to filter out all the elements of an iterable, based on if a condition evaluates to treu&lt;br&gt;
**Syntax :- *filter(callable, iterable)&lt;/em&gt;*&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It takes first argument as function which evaluates to some boolean condition &lt;em&gt;(True or False)&lt;/em&gt;, second argument as &lt;em&gt;iterable&lt;/em&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The element will only be included if the function return **&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;for n size of input , it will return &lt;strong&gt;n-m&lt;/strong&gt; size output&lt;br&gt;
where m is the no. of element for which the function evaluates to &lt;em&gt;False&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's see some example of &lt;em&gt;filter()&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Task :- fitler ints from a list of object of various type i.e. (float,string,lst,...)&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [12, 43.42, 'hello', [1,3,4], 54,92, (1,2), 12.22, 9]
print("Orignal list of object without filteration :- ",lst)

lst_of_ints = list(filter(lambda x:type(x)== int, lst))
print("Updated list of ints  :- ",lst_of_ints)

Output :-
Orignal list of object without filteration :-  [12, 43.42, 'hello', [1, 3, 4], 54, 92, (1, 2), 12.22, 9]
Updated list of ints  :-  [12, 54, 92, 9]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In the above example we have filtered &lt;em&gt;ints&lt;/em&gt; from  a list of objects of different &lt;em&gt;type&lt;/em&gt;, we used the same approch as in the previous example, but not here we're using a function which evaluates to two condition ,&lt;em&gt;i.e., if the type of object is int then it returning True, and that element get included in the result list , Otherwise if the type in not int then it returning False , means item will not be included in  the result list&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;let's see some other example :-&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Task :- filter even integer from a list of integers&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;list_of_ints = [1,2,3,4,5,6,7,8,9,10]

print("Orignal list of ints :- ",list_of_ints)

list_of_even_ints = list(filter(lambda x: x % 2 ==0, list_of_ints))
print("Updated list of only even ints  :- ",list_of_even_ints)

Output :- 
Orignal list of ints :-  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Updated list of only even ints  :-  [2, 4, 6, 8, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In the above example we filtered list of even integer from a  list of integers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Task :- we have a list of random emails, so of which are valid and some are invalid , we have to filter out only valid emails&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import re
list_of_emails = ['nullchar@aol.com',
                  'salesgeek@yahoo.com',
                  'luebkehotmail.com',
                  'fmergeslive.com',
                  'jonathan@outlook.com',
                  'lydia@gmail.com',
                  'grdschl@comcast.net',
                  'catalogsbcglobal.net',
                  'glenz@outlook.com',
                  'cumarana@outlook.com',
                  'rsteinericloud.com',
                  'mosses@mac.com']

email_regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

print("Orignal list of emails :- ",list_of_emails,"\n")

valid_emails = list(filter(lambda email:re.match(email_regex, email), list_of_emails))
print("Updated list of valid emails  :- ",valid_emails)

Output :-
Orignal list of emails :-  ['nullchar@aol.com', 'salesgeek@yahoo.com', 'luebkehotmail.com', 'fmergeslive.com', 'jonathan@outlook.com', 'lydia@gmail.com', 'grdschl@comcast.net', 'catalogsbcglobal.net', 'glenz@outlook.com', 'cumarana@outlook.com', 'rsteinericloud.com', 'mosses@mac.com']

Updated list of valid emails  :-  ['nullchar@aol.com', 'salesgeek@yahoo.com', 'jonathan@outlook.com', 'lydia@gmail.com', 'grdschl@comcast.net', 'glenz@outlook.com', 'cumarana@outlook.com', 'mosses@mac.com']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In the above example we make use of &lt;em&gt;re&lt;/em&gt; regex module to match if the email is valid or not using the &lt;strong&gt;regular expression&lt;/strong&gt; in &lt;em&gt;email_regex&lt;/em&gt; variable, and after iterating over each element at matching it to the &lt;em&gt;email_regex&lt;/em&gt; we get a list of valid emails&lt;/p&gt;
&lt;h3&gt;
  
  
  3. &lt;em&gt;reduce()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The function &lt;em&gt;reduce(function, sequence)&lt;/em&gt; continually applies the function to the sequence. It then returns a single value.
&lt;strong&gt;Syntax :- *reduce(callable, iterable)&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;i.e., If seq = [ s1, s2, s3, ... , sn ], calling reduce(function, sequence) works like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;At first the first two elements of seq will be applied to function, i.e. func(s1,s2)&lt;/li&gt;
&lt;li&gt;The list on which reduce() works looks now like this: [ 
function(s1, s2), s3, ... , sn ]&lt;/li&gt;
&lt;li&gt;In the next step the function will be applied on the previous result and the third element of the list, i.e. function(function(s1, s2),s3)&lt;/li&gt;
&lt;li&gt;The list looks like this now: [ function(function(s1, s2),s3), ... , sn ]

&lt;ol&gt;
&lt;li&gt;It continues like this until just one element is left and return this element as the result of reduce()&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;let's see some example of &lt;em&gt;reduce()&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Task :- reduce a list of int to a single integer using + operator&lt;/strong&gt; &lt;/p&gt;
&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from functools import reduce

lst =[47,11,42,13]
print("Original list :- ",lst)
print("reduced value :- ",reduce(lambda x,y: x+y,lst))

Output :-
Original list :-  [47, 11, 42, 13]
reduced value :-  113
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;let me explain what is going on in the above example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;45    11     42    13
 \    /      /     /
  \  /      /     /
   58      /     /
    \     /     /
     \   /     /
      100     /
       \     /
        \   /
         \ /
         113

numbers at index 0 and 1 first added
then their sum added with value at index 3
then their sum added with value at index 4
then after completing the sequence 
we the reduced value  :- 113

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let's see one more example of reduce&lt;br&gt;
&lt;strong&gt;Task :- reduce a list of int to a single integer using * operator&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from functools import reduce

lst =[47,11,42,13]
print("Original list :- ",lst)
print("reduced value :- ",reduce(lambda x,y: x*y,lst))

Output :-
Original list :-  [47, 11, 42, 13]
reduced value :-  282282
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The visual that i have demostrated in the previous example ,in this example the same process going , but this time using &lt;em&gt;x&lt;/em&gt; operator.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. &lt;em&gt;zip()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The function &lt;em&gt;zip()&lt;/em&gt; makes an iterator that combines elements from each of the iterables&lt;br&gt;
&lt;strong&gt;Syntax :- zip(iter1, iter2, iter3, iter4....)&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;zip()&lt;/em&gt; function return &lt;em&gt;zip object&lt;/em&gt; which iterate over a list of &lt;em&gt;tuples&lt;/em&gt;  where tuples size is equal to the no. of list passed in the &lt;em&gt;zip()&lt;/em&gt; function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The iterator stops when the shortest input iterable is exhausted&lt;br&gt;
&lt;em&gt;i.e it will return list of tuples of size equal to the length of (minimum size *iterable&lt;/em&gt; among all the &lt;em&gt;iterables&lt;/em&gt; passed in the &lt;em&gt;zip()&lt;/em&gt; function)*&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's see some example of &lt;em&gt;zip()&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Task :- we will combine user firstname,lastname,hometown using &lt;br&gt;
zip() function&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;first_names = ['ram','shyam','ajay','bipin','manoj','alex']
print("list of first names :- ", first_names,"\n")

last_names = ['gupta','tiwari','yadav','rawat','desai','khan','raven']
print("list of first names :- ", last_names,"\n")

home_towns = ['ayodhya','vrindavan','bihar','jhnasi','boston','delhi','lanka']
print("list of hometowns :-" , home_towns,"\n")


persons_info = list(zip(first_names,last_names,home_towns))
print("data after using zip() function :-",persons_info)

Output :-
list of first names :-  ['ram', 'shyam', 'ajay', 'bipin', 'manoj', 'alex'] 

list of first names :-  ['gupta', 'tiwari', 'yadav', 'rawat', 'desai', 'khan', 'raven'] 

list of hometowns :- ['ayodhya', 'vrindavan', 'bihar', 'jhnasi', 'boston', 'delhi', 'lanka'] 

data after using zip() function :- [('ram', 'gupta', 'ayodhya'), ('shyam', 'tiwari', 'vrindavan'), ('ajay', 'yadav', 'bihar'), ('bipin', 'rawat', 'jhnasi'), ('manoj', 'desai', 'boston'), ('alex', 'khan', 'delhi')]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we have combined inforation from three iterable (firstnames,lastnames,hometowns) into list of tuples with information combined from all three iterables.&lt;/p&gt;

&lt;p&gt;also notice that,&lt;br&gt;
&lt;em&gt;it has returned a list of tuples of size equal to the length of (minimum size *iterable&lt;/em&gt; among all the &lt;em&gt;iterables&lt;/em&gt; passed in the &lt;em&gt;zip()&lt;/em&gt; function)&lt;br&gt;
i.e &lt;br&gt;
    * &lt;em&gt;first_names&lt;/em&gt; list has &lt;em&gt;length&lt;/em&gt; of 6&lt;br&gt;
    * &lt;em&gt;last_names&lt;/em&gt; list has &lt;em&gt;length&lt;/em&gt; of 6&lt;br&gt;
    * &lt;em&gt;home_town&lt;/em&gt; list has &lt;em&gt;length&lt;/em&gt; of 7&lt;/p&gt;

&lt;h3&gt;
  
  
  5. &lt;em&gt;enumerate()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The function &lt;em&gt;enumerate()&lt;/em&gt; return an iterates to a list of tuples , where  first element of each tuple is it's corresponding index (by default is 0) and second element is the value at store at the index&lt;br&gt;
&lt;strong&gt;Syntax :- enumerate(iterable, start)&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;the second argument &lt;em&gt;start&lt;/em&gt; denotes from where the index start &lt;br&gt;
&lt;em&gt;i.e.,&lt;/em&gt; if start = 4 then [(value1,4), (value2,5), (value3,6)...]&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's us take an example with start argument and without start arguement&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Task :- without start argument&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = ['ram','shyam','ajay','bipin','manoj','alex']

names_with_indexes = list(enumerate(names))
for name in names_with_indexes:
  print(name)

Output :-
(0, 'ram')
(1, 'shyam')
(2, 'ajay')
(3, 'bipin')
(4, 'manoj')
(5, 'alex')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Task :- with start argument&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names = ['ram','shyam','ajay','bipin','manoj','alex']

names_with_indexes = list(enumerate(names, 4))
for name in names_with_indexes:
  print(name)

Output :-
(4, 'ram')
(5, 'shyam')
(6, 'ajay')
(7, 'bipin')
(8, 'manoj')
(9, 'alex')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;you can see the difference in the above two examples&lt;/p&gt;

&lt;h3&gt;
  
  
  6. &lt;em&gt;all()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;all()&lt;/em&gt; are built-in functions that allow us to conveniently check for boolean matching in an iterable.&lt;br&gt;
&lt;strong&gt;Syntax :- all(iterable)&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;all() will return True if all elements in an iterable are True.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's understand with examples&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [True,True,False,True]
print(all(lst))

Output :-
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since element at index 2 is false , &lt;em&gt;all()&lt;/em&gt; returned &lt;em&gt;False&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [True,True,True,True]
print(all(lst))

Output :-
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the result is &lt;em&gt;True&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [True,[],[1,2,3],True]

print(all(lst))

Output :-
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;if any one coufused why the result is &lt;em&gt;False&lt;/em&gt;, there is a concept of &lt;em&gt;Truthy and Falsy&lt;/em&gt; in python.&lt;br&gt;
here is a good example your can check &lt;a href="https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false"&gt;&lt;em&gt;Truthy and Falsy&lt;/em&gt; in python&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  7. &lt;em&gt;any()&lt;/em&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;any()&lt;/em&gt; are built-in functions that allow us to conveniently check for boolean matching in an iterable.&lt;br&gt;
&lt;strong&gt;Syntax :- any(iterable)&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;any() will return True if any elements in an iterable are True.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's understand with examples&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [True,False,False,False]
print(any(lst))

Output :-
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since element at index 0 is True, &lt;em&gt;any()&lt;/em&gt; returned &lt;em&gt;True&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [False,False,False,False]
print(any(lst))

Output :-
False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the result is &lt;em&gt;False&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lst = [(),[],[1,2,3],False]

print(any(lst))

Output :-
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the result is true because at index 2, there is a &lt;em&gt;list&lt;/em&gt; of size greater than 0 , which is a Truthy value.&lt;/p&gt;

&lt;p&gt;with this example we have come to an end,&lt;br&gt;
we have covered various useful &lt;em&gt;built-in&lt;/em&gt; functions&lt;br&gt;
which are very useful in certain scenarios&lt;/p&gt;

&lt;p&gt;Hope you all have learned some useful stuff today. :-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
      <category>functional</category>
    </item>
    <item>
      <title>Getting Started with Collections Module in Python</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Thu, 11 Nov 2021 10:52:03 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/getting-started-with-collections-module-in-python-5ea9</link>
      <guid>https://dev.to/adarshrawat7400/getting-started-with-collections-module-in-python-5ea9</guid>
      <description>&lt;p&gt;In This Article we will go through various example covering the data structures &lt;strong&gt;containers&lt;/strong&gt; offered by python collections module.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;collections&lt;/em&gt; module provide us with various different &lt;em&gt;container&lt;/em&gt; datatypes, which are used to stored objects, and &lt;br&gt;
access them, iterate over the objects, these all &lt;em&gt;container&lt;/em&gt; datatypes , all have there usecases, which we will look later in the Article.&lt;/p&gt;

&lt;p&gt;Before going forward, i'd like to mention one more point, all the &lt;em&gt;container&lt;/em&gt; datatypes are built on top of the existing datatypes available in python like &lt;em&gt;(Tuple,List,Set,Dict)&lt;/em&gt;, these are introduced  to improve the functionalities of the built-in  &lt;em&gt;container&lt;/em&gt; datatype in python. &lt;br&gt;
As we progess further in the Article things will get clear to you.&lt;/p&gt;

&lt;p&gt;We will going to the look at &lt;em&gt;containers&lt;/em&gt; available in &lt;em&gt;collections&lt;/em&gt; module :-&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;em&gt;Counters&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;OrderedDict&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;DefaultDict&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;ChainMap&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;NamedTuple&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;DeQue&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;to use &lt;em&gt;containers&lt;/em&gt; available in &lt;em&gt;collections&lt;/em&gt; module, you will first have to import them,&lt;br&gt;
there are mutiple ways to import :-&lt;/p&gt;
&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#Import all container at once
from collections import *

#Import single container
from collections import Counter

# Importing and accessing using alias
import collections as clns
counter = clns.Counter()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  1. Counter :-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;A Counter is a sub-class of the dictionary.&lt;/li&gt;
&lt;li&gt;It is used to keep the count of the elements in an iterable&lt;/li&gt;
&lt;li&gt;It is an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from collections import Counter

names = ['George', 'Paul', 'George', 'Ringo', 'John', 'John', 'George', 'John', 'Ringo', 'Paul', 'Ringo', 'Ringo', 'George', 'Paul', 'John', 'John', 'John', 'John', 'John', 'Paul']

names_counter = Counter(names)
print(names_counter)

Output :- 
Counter({'John': 8, 'George': 4, 'Paul': 4, 'Ringo': 4})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can see that it return &lt;em&gt;Counter&lt;/em&gt; object , which we can &lt;em&gt;cast&lt;/em&gt; to &lt;em&gt;dict&lt;/em&gt; for further use.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;key as the name&lt;/li&gt;
&lt;li&gt;value as the no. of occourances of that key&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Counter &lt;em&gt;container&lt;/em&gt; has &lt;em&gt;most_common&lt;/em&gt; method which returns List the n most common elements and their counts from the most common to the least.  If n is None, then list all element counts.&lt;/p&gt;

&lt;p&gt;calling  &lt;em&gt;most_common()&lt;/em&gt; on &lt;em&gt;names_counter&lt;/em&gt; will return in :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;names_counter.most_common()

Output :-
[('John', 8), ('George', 4), ('Paul', 4), ('Ringo', 4)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;where the most frequent element with its count  is at the from and least frequent element with its count at the end of the list&lt;br&gt;
to know more about other methods available in &lt;em&gt;Counter&lt;/em&gt; use can call &lt;em&gt;help(counter_object)&lt;/em&gt; which will give you &lt;em&gt;documentation&lt;/em&gt; for &lt;em&gt;Counter&lt;/em&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  2. OrderedDict:-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;A OrderedDict is a sub-class of the dictionary.&lt;/li&gt;
&lt;li&gt;It remember the order in which the keys are inserted.&lt;/li&gt;
&lt;li&gt;A regular &lt;em&gt;dict&lt;/em&gt; does not preserve the order in which the keys are inserted but an &lt;em&gt;OrderedDict&lt;/em&gt; maintains the order in which keys are inserted , , , , this is the major difference between a regular &lt;em&gt;dict&lt;/em&gt; and an &lt;em&gt;OrderedDict&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Regular dict
reg_dict = dict()
reg_dict['apples']  = 3
reg_dict['pineapple'] = 5
reg_dict['mango'] = 1
reg_dict['orange'] = 7
reg_dict['grapes'] = 2
print(f"Regular Dict {reg_dict} \n\n")

from collections import OrderedDict

# Ordered Dict
ord_dict = OrderedDict()
ord_dict['apples']  = 3
ord_dict['pineapple'] = 5
ord_dict['mango'] = 1
ord_dict['orange'] = 7
ord_dict['grapes'] = 2
print(f"Ordered Dict {ord_dict}")

Regular Dict {'apples': 3, 'pineapple': 5, 'mango': 1, 'orange': 7, 'grapes': 2} 


Ordered Dict OrderedDict([('apples', 3), ('pineapple', 5), ('mango', 1), ('orange', 7), ('grapes', 2)])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Deleting elment from &lt;em&gt;OrderedDict&lt;/em&gt; :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;del ord_dict['mango']
print(ord_dict)

Output :-
OrderedDict([('apples', 3), ('pineapple', 5), ('orange', 7), ('grapes', 2)])


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inserting element in &lt;em&gt;OrderedDict&lt;/em&gt; :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ord_dict['mango'] = 11
print(ord_dict)

Output :-
OrderedDict([('apples', 3), ('pineapple', 5), ('orange', 7), ('grapes', 2), ('mango', 11)])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see first we deleted the key &lt;em&gt;mango&lt;/em&gt; from &lt;em&gt;OrderedDict&lt;/em&gt; then re-inserted it at the end of the &lt;em&gt;OrderedDict&lt;/em&gt;.&lt;br&gt;
for more method use can call &lt;em&gt;help(OrderedDict_object)&lt;/em&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  3. DefaultDict :-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;A DefaultDict is a sub-class of the dictionary.&lt;/li&gt;
&lt;li&gt;The functionality of both dictionaries and defualtdict are almost same except for the fact that defualtdict never raises a &lt;em&gt;KeyError&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;It provides a default value for the key that does not exists.&lt;/li&gt;
&lt;li&gt;We can pass a default values while initialising the DefaultDict as *DefaultDict(default_value=None)&lt;/li&gt;
&lt;li&gt;It can take any type of default value&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
from collections import defaultdict

d_dict = defaultdict(lambda : "Not Available") # passing default value

d_dict['John'] = 11
d_dict['Paul'] = 12
d_dict['George'] = 9
d_dict['Rango'] = 14

print(d_dict['Rango'])
print(d_dict['John'])
print(d_dict['max'])

Output :-
14
11
Not Available
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  4. ChainMap :-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;A ChainMap is a &lt;em&gt;container&lt;/em&gt; which stores many &lt;em&gt;dictionaries&lt;/em&gt; into single &lt;em&gt;ChainMap&lt;/em&gt; object.&lt;/li&gt;
&lt;li&gt;We can perform operations on &lt;em&gt;ChainMap&lt;/em&gt; object using following methods :-&lt;/li&gt;
&lt;li&gt;keys() :- This function is used to display all the keys of all the dictionaries in ChainMap.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;values() :- This function is used to display values of all the dictionaries in ChainMap.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;maps() :- This function is used to display keys with corresponding values of all the dictionaries in ChainMap.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from collections import ChainMap  


d1 = {'Ram': 12, 'Shyam': 12} 
d2 = {'Mango': 3, 'Orange': 4} 
d3 = {'Car': 4, 'Bus': 8} 

# Defining the chainmap  
c = ChainMap(d1, d2, d3)  

print(c)

Output :- 
ChainMap({'Ram': 12, 'Shyam': 12}, {'Mango': 3, 'Orange': 4}, {'Car': 4, 'Bus': 8})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
# printing chainMap using maps
print ("All the ChainMap contents are : ")
print (c.maps)

# printing keys using keys()
print ("All keys of ChainMap are : ")
print (list(c.keys()))

# printing keys using keys()
print ("All values of ChainMap are : ")
print (list(c.values()))

Output :-

All the ChainMap contents are : 
[{'Ram': 12, 'Shyam': 12}, {'Mango': 3, 'Orange': 4}, {'Car': 4, 'Bus': 8}]
All keys of ChainMap are : 
['Car', 'Bus', 'Mango', 'Orange', 'Ram', 'Shyam']
All values of ChainMap are : 
[4, 8, 3, 4, 12, 12]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  5. NamedTuple:-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;It contain keys that are hashed to a particular value.&lt;/li&gt;
&lt;li&gt;It supports both access from key-value and iteration.&lt;/li&gt;
&lt;li&gt;following methods are availble in &lt;em&gt;namedtuple&lt;/em&gt; to access the value :-&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;access by index:  we can pass index within square brackets to  access the value ,unlike dictionaries which are not accessible by index.&lt;/li&gt;
&lt;li&gt;access by keyname: access value by using &lt;em&gt;.&lt;/em&gt; operator followed by name of the attribute.&lt;/li&gt;
&lt;li&gt;access using getattr(): This is another way to access the value by giving namedtuple and key value as its argument.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from collections import namedtuple

Book = namedtuple('Book', ['title', 'author', 'price'])

b = Book('Xyz', 'xyz', 50)

print("accessing using index")
print(b[0])
print(b[1])
print(b[2])

print("\n------------------\n")

print("accessing using name")
print(b.title)
print(b.author)
print(b.price)

print("\n------------------\n")

print("using getattr() ")
print(getattr(b, 'title'))
print(getattr(b, 'author'))
print(getattr(b, 'price'))

Output :-
accessing using index
Xyz
xyz
50

------------------

accessing using name
Xyz
xyz
50

------------------

using getattr() 
Xyz
xyz
50
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  6. DeQue:-
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;Deque&lt;/em&gt; (Doubly Ended Queue) in Python is implementation available in &lt;em&gt;collections&lt;/em&gt; module&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Deque&lt;/em&gt; helps in fast insertion and deletion operation which 
&lt;em&gt;list&lt;/em&gt; datatypes lacks &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Deque&lt;/em&gt; offers insertion and deletion in &lt;em&gt;O(1) time complexity&lt;/em&gt;
whereas &lt;em&gt;list&lt;/em&gt; offer insetion and deletion in &lt;em&gt;O(n) time complexity&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;It offers operations :-&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;append() :- This function is used to insert the value in its argument to the right end of deque.&lt;/li&gt;
&lt;li&gt;appendleft() :- This function is used to insert the value in its argument to the left end of deque.&lt;/li&gt;
&lt;li&gt;pop() :- This function is used to delete an argument from the right end of deque.&lt;/li&gt;
&lt;li&gt;popleft() :- This function is used to delete an argument from the left end of deque.
these are the frequenty used methods, you can find other method by calling &lt;em&gt;help(deque_object)&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from collections import deque

# initializing deque
dq = deque(['John','Max','Harry','Marcus','Robin','Jackub'])

# using append() to insert element at right end
dq.append("Jimmy")

print ("The deque after appending at right is : ")
print (dq,"\n")

# using appendleft() to insert element at left end
dq.appendleft('Alex')
print ("The deque after appending at left is : ")
print (dq,"\n")

# using pop() to delete element from right end
dq.pop()
print ("The deque after deleting from right is : ")
print (dq,"\n")

# using popleft() to delete element from left end
dq.popleft()
print ("The deque after deleting from left is : ")
print (dq,"\n")

Output :-

The deque after appending at right is : 
deque(['John', 'Max', 'Harry', 'Marcus', 'Robin', 'Jackub', 'Jimmy']) 

The deque after appending at left is : 
deque(['Alex', 'John', 'Max', 'Harry', 'Marcus', 'Robin', 'Jackub', 'Jimmy']) 

The deque after deleting from right is : 
deque(['Alex', 'John', 'Max', 'Harry', 'Marcus', 'Robin', 'Jackub']) 

The deque after deleting from left is : 
deque(['John', 'Max', 'Harry', 'Marcus', 'Robin', 'Jackub']) 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have completed 6  &lt;em&gt;containers&lt;/em&gt; available in  the &lt;em&gt;collections&lt;/em&gt; module , there are other &lt;em&gt;container&lt;/em&gt; datatype available in &lt;em&gt;collections&lt;/em&gt; module you can check by clicking the link below :-&lt;br&gt;
&lt;a href="https://docs.python.org/3/library/collections.html"&gt;other collections module &lt;em&gt;containers&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hope you guys have learned all the topics covered in this Article :-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
      <category>collections</category>
    </item>
    <item>
      <title>Getting Started with Decorators in Python</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Wed, 10 Nov 2021 16:55:18 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/getting-started-with-decorators-in-python-4kpi</link>
      <guid>https://dev.to/adarshrawat7400/getting-started-with-decorators-in-python-4kpi</guid>
      <description>&lt;p&gt;To get started with Decorators , First we have to understand few things :-&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;everything we see in python is an object.&lt;/li&gt;
&lt;li&gt;function in python is also an object.&lt;/li&gt;
&lt;li&gt;we can declare function within a function.&lt;/li&gt;
&lt;li&gt;these inner function have access to local variables in th e enclosing function. &lt;/li&gt;
&lt;li&gt;a function can return any value, including a function&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;to understand the above point let us take an example&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; def hello(name):
...     return f"Hello {name}"
...
&amp;gt;&amp;gt;&amp;gt; a = hello
&amp;gt;&amp;gt;&amp;gt; # as we can see variable a referencing to a function object
&amp;gt;&amp;gt;&amp;gt; a("Ram")
'Hello Ram'
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;with the above example we can,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;functions are objects &lt;/li&gt;
&lt;li&gt;they can be assigned/reference by other name ,such as variable &lt;em&gt;a&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let's take another example to clear other remaining &lt;br&gt;
points&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; def foo(name):
...     def bar():
...             print(f"Hey I'm the inner function bar enclosed inside foo function , {name}")
...     return bar
...
&amp;gt;&amp;gt;&amp;gt; f = foo("Ram")
&amp;gt;&amp;gt;&amp;gt; f.__name__
'bar'
&amp;gt;&amp;gt;&amp;gt; type(f)
&amp;lt;class 'function'&amp;gt;
&amp;gt;&amp;gt;&amp;gt; f()
Hey I'm the inner function bar enclosed inside foo function , Ram
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we have declared a function &lt;em&gt;foo&lt;/em&gt; which contains another function &lt;em&gt;bar&lt;/em&gt;, and when we called the outer function &lt;em&gt;foo&lt;/em&gt; we get back reference to &lt;em&gt;bar&lt;/em&gt; function object,&lt;br&gt;
we also verified the same by,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;checking &lt;em&gt;f.&lt;strong&gt;name&lt;/strong&gt;&lt;/em&gt; attribute which return name of the function&lt;/li&gt;
&lt;li&gt;&lt;p&gt;checked &lt;em&gt;type(f)&lt;/em&gt; to see that it is of type &lt;em&gt;function&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inner function &lt;em&gt;bar&lt;/em&gt; has access to  all varibles of enclosing function like variable &lt;em&gt;name&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The concepts that we have covered in the above example&lt;br&gt;
will help in the understanding of Decorators&lt;/p&gt;

&lt;p&gt;Now we see some examples of special type of decorator&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Function Wrapper&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Wrappers around the functions are also knows as decorators which are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class.&lt;/p&gt;

&lt;p&gt;Let's understand with an example&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lines = '-' * 60 + '\n'

def with_lines(func):
    def wrapper():
        return f'{lines}{func()}{lines}'
    return wrapper

def a():
    return f'I am in a!\n'
new_a = with_lines(a)


def b():
    return f'I am in b!\n'
new_b = with_lines(b)

print(a())
print(b())
print(new_a())
print(new_b())

Output :-
I am in a!

I am in b!

------------------------------------------------------------
I am in a!
------------------------------------------------------------

------------------------------------------------------------
I am in b!
------------------------------------------------------------


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we created a &lt;em&gt;with_lines&lt;/em&gt; function which takes &lt;em&gt;func&lt;/em&gt; (callable object ) as and argument and &lt;em&gt;with_lines&lt;/em&gt; function has an inner function &lt;em&gt;wrapper&lt;/em&gt;&lt;br&gt;
which has access to the outer function variable, &lt;br&gt;
So we call the function passed by outer function inside the &lt;strong&gt;wrapper&lt;/strong&gt; function by adding &lt;em&gt;global varible&lt;/em&gt; lines at the start and end and return wrapper function object.&lt;/p&gt;

&lt;p&gt;With this now we have a &lt;em&gt;with_lines&lt;/em&gt; function wrapper which can we used with any function to change behiviour of the function,&lt;/p&gt;

&lt;p&gt;As we used it with  &lt;em&gt;new_a&lt;/em&gt; and &lt;em&gt;new_b&lt;/em&gt; functions that have some formating added to them using &lt;em&gt;with_lines&lt;/em&gt; wrapper function.&lt;/p&gt;

&lt;p&gt;Wrapper are one of the most powerful tools of python which can we used to change or added some extra behiviour to the existing function.&lt;/p&gt;

&lt;p&gt;Now we have gathered enough information to understand &lt;em&gt;Decorators&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a Decorator?
&lt;/h3&gt;

&lt;p&gt;In simple terms :-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A function&lt;/li&gt;
&lt;li&gt;that takes function as an argument &lt;/li&gt;
&lt;li&gt;and return a function as its output&lt;/li&gt;
&lt;li&gt;Because of the &lt;strong&gt;@&lt;/strong&gt; syntax in Python, decorating a function replaces that function with the result of calling the decorator on the function.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  What can I use a Decorator For?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Anything that is repeated across multiple functions&lt;/li&gt;
&lt;li&gt;Grab / modify / filter input arguments&lt;/li&gt;
&lt;li&gt;Grab / modify / filter outputs&lt;/li&gt;
&lt;li&gt;Change the state&lt;/li&gt;
&lt;li&gt;Stop a function from being called under certain conditions&lt;/li&gt;
&lt;li&gt;Choose a different function to be called instead&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now we will understand decorators with couple of examples&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lines = '-' * 60 + '\n'

def with_lines(func):
    def wrapper(*args, **kwargs):
        return f'{lines}{func(*args, **kwargs)}{lines}'
    return wrapper

@with_lines
def a():
    return f'I am in a!\n'
# a = with_lines(a)   # this line (after) is the same as @with_lines (before)


@with_lines
def b():
    return f'I am in b!\n'
# b = with_lines(b)  # this line (after) is the same as line 14

@with_lines
def add(x, y):
    return f'{x} + {y} = {x+y}\n'

print(a())
print(b())
print(add(3,5))  # add is actually wrapper! so when I call add(3,5), it's saying wrapper(3,5)

OUTPUT :- 

------------------------------------------------------------
I am in a!
------------------------------------------------------------

------------------------------------------------------------
I am in b!
------------------------------------------------------------

------------------------------------------------------------
3 + 5 = 8
------------------------------------------------------------

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the same &lt;em&gt;with_lines&lt;/em&gt; wrapper function used in the above example we added this decorator with the existing method &lt;em&gt;a()&lt;/em&gt; ,&lt;em&gt;b()&lt;/em&gt; and &lt;em&gt;add()&lt;/em&gt; method using using &lt;strong&gt;@&lt;/strong&gt; Symbol which replaces that function with the result of calling the decorator on the function.&lt;/p&gt;

&lt;p&gt;Let's take another example to see how we can filter the input using decorator :-&lt;br&gt;
We have given a list of int from which we have to all numbers which are only even, let's see how we can do it using &lt;em&gt;decorator&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

# Wrapper that filter even from list of ints
def only_evens(func):
    def wrapper(*args):
        even_numbers = [num for num in args if num % 2 == 0]
        print("\n\nWrapper added")
        print(f"even numbers {even_numbers}")
        result = f"sum of even numbers :- {func(*even_numbers)}"
        return result

    return wrapper



def add_nums(*numbers):
    sum = 0
    for num in numbers:
        sum += num
    return sum


print("Original add_nums function output :-",add_nums(1,2,3,4,5,6,7,8,9,10))

@only_evens
def add_nums(*numbers):
    sum = 0
    for num in numbers:
        sum += num
    return sum


print("Original add_nums function output :-",add_nums(1,2,3,4,5,6,7,8,9,10))

Output :-
Original add_nums function output :- 55


Wrapper added
even numbers [2, 4, 6, 8, 10]
Original add_nums function output :- sum of even numbers :- 30

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example &lt;br&gt;
first we called the orignal method &lt;em&gt;add_nums()&lt;/em&gt; which add all the numbers.&lt;br&gt;
then we declared the &lt;em&gt;add_nums()&lt;/em&gt; function again but this time &lt;br&gt;
added &lt;strong&gt;@only_evens&lt;/strong&gt; wrapper to it , the  wrapper &lt;em&gt;only_evens&lt;/em&gt; filter the list of values first then the filters values passed to the original method &lt;em&gt;add_nums()&lt;/em&gt; which return the sum of only even values.&lt;/p&gt;

&lt;p&gt;with this example we have come to an end,&lt;br&gt;
hope you all have learn some basis of &lt;em&gt;decorators&lt;/em&gt;&lt;br&gt;
this topic , at first is not easy to grasp,&lt;br&gt;
but as you explore more about &lt;em&gt;decorators&lt;/em&gt;&lt;br&gt;
you will know how useful it is.&lt;br&gt;
See you next time :-)&lt;/p&gt;

</description>
      <category>progamming</category>
      <category>python</category>
      <category>beginners</category>
      <category>decorators</category>
    </item>
    <item>
      <title>Types of iterators in Python, Which One to Use?</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Wed, 10 Nov 2021 10:34:53 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/types-of-iterators-in-python-which-one-to-use-59h</link>
      <guid>https://dev.to/adarshrawat7400/types-of-iterators-in-python-which-one-to-use-59h</guid>
      <description>&lt;p&gt;&lt;strong&gt;In this Article we will write&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;code for various iterators in python&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;comparing the time taken by the iterator to iterate&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;when to use which iterator&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;if you're new to this topic, i would prefer you go with this article linked below first:-&lt;/em&gt;*&lt;/p&gt;

&lt;p&gt;---&amp;gt; &lt;a href="https://dev.to/adarshrawat7400/what-is-iterableiterator-in-python-3325"&gt;What is iterator,iterable in Python&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Types of Iterators in Python&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Forward Iterator (for iterator)&lt;/li&gt;
&lt;li&gt;Reverse Iterator&lt;/li&gt;
&lt;li&gt;Index Based Iterator&lt;/li&gt;
&lt;li&gt;Enumerate Iterator&lt;/li&gt;
&lt;li&gt;Parallel Iterator&lt;/li&gt;
&lt;li&gt;File Iterator&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Forward Iterator&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;It is a read-only iterator, means you can only travese over it items in iterable, cannot modify values&lt;/li&gt;
&lt;li&gt;It is the fastest way to iterate/traverse over the iterable (&lt;em&gt;Collection on values&lt;/em&gt;)&lt;/li&gt;
&lt;li&gt;As it's name suggest it can move only forward, going at the previous element is not possible.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; names = ['ram','shyam','ajay','bipin','manoj','alex']
&amp;gt;&amp;gt;&amp;gt; for name in names:
...     name = name.upper()
...     print(name)
...
RAM
SHYAM
AJAY
BIPIN
MANOJ
ALEX
&amp;gt;&amp;gt;&amp;gt; names
['ram', 'shyam', 'ajay', 'bipin', 'manoj', 'alex']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see in the above example &lt;em&gt;for loop&lt;/em&gt; uses forward iterator,to iterable over the name in the &lt;em&gt;names&lt;/em&gt; list,&lt;br&gt;
&lt;strong&gt;we also tried to modify each value, by explicitly assigining &lt;br&gt;
it to new uppercase value but, it does not modifiy the name in the names list, as we can see on the last line&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Reverse Iterator&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;It is a read-only iterator, means you can only travese over it items in iterable, cannot modify values&lt;/li&gt;
&lt;li&gt;Iterate over element in the reverse order ,starting from last element to first element in the iterable.&lt;/li&gt;
&lt;li&gt;it has same efficiency as forward itertor&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;reversed()&lt;/em&gt; function is used to return &lt;em&gt;list_reverseiterator object&lt;/em&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; names
['ram', 'shyam', 'ajay', 'bipin', 'manoj', 'alex']
&amp;gt;&amp;gt;&amp;gt; reverse_iter = reversed(names)
&amp;gt;&amp;gt;&amp;gt; reverse_iter
&amp;lt;list_reverseiterator object at 0x000001D28CA21D20&amp;gt;
&amp;gt;&amp;gt;&amp;gt; for name in reverse_iter:
...     print(name)
...
alex
manoj
bipin
ajay
shyam
ram
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reversed object return &lt;em&gt;list_reverseiterator&lt;/em&gt; object which then traveres from last element to first element.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Index Based Iterator&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;It uses a special function -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;range(start,stop,stepby),&lt;/li&gt;
&lt;li&gt;range(start,stop),&lt;/li&gt;
&lt;li&gt;range(stop)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Suitable when we have to perfrom read/write operation on the iterable object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Suitable for &lt;em&gt;INPLACE&lt;/em&gt; list operations&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is slower compared to for iterator&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; names = ['ram','shyam','ajay','bipin','manoj','alex']
&amp;gt;&amp;gt;&amp;gt; for i in range(len(names)):
...     names[i] = names[i].upper()
...     print(names[i])
...
RAM
SHYAM
AJAY
BIPIN
MANOJ
ALEX
&amp;gt;&amp;gt;&amp;gt; names
['RAM', 'SHYAM', 'AJAY', 'BIPIN', 'MANOJ', 'ALEX']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see we used &lt;em&gt;range()&lt;/em&gt; function to traverse/iterate over the list using &lt;em&gt;index&lt;/em&gt;, and also able to modify the value &lt;em&gt;INPLACE&lt;/em&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Enumerate Iterator&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;It uses a special function -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;enumerate(iterable)&lt;/em&gt;, 
return &lt;em&gt;enumerate&lt;/em&gt; object&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Suitable for &lt;em&gt;Mutable&lt;/em&gt; iterable objects&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Can be used for &lt;em&gt;INPLACE&lt;/em&gt; Operations&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Slow as compared to forward Iterator&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; names = ['ram','shyam','ajay','bipin','manoj','alex']
&amp;gt;&amp;gt;&amp;gt; names_iter = enumerate(names)
&amp;gt;&amp;gt;&amp;gt; names_iter
&amp;lt;enumerate object at 0x000001D28CA413C0&amp;gt;
&amp;gt;&amp;gt;&amp;gt; for index,value in names_iter:
...     names[index] = value.upper()
...
&amp;gt;&amp;gt;&amp;gt; names
['RAM', 'SHYAM', 'AJAY', 'BIPIN', 'MANOJ', 'ALEX']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;enumerate()&lt;/em&gt; function return &lt;em&gt;enumerate object&lt;/em&gt; which iterate over a list of &lt;em&gt;tuples&lt;/em&gt; where&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;first element of each tuple is it's corresponding index &lt;/li&gt;
&lt;li&gt;second element is the value at store at the index&lt;/li&gt;
&lt;li&gt;with the help of index we can modify the value in the &lt;em&gt;names&lt;/em&gt; list&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Parallel Iterator&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;It uses a special function -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;zip(iter1, iter2, iter3, iter4....)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Suitable when we have to &lt;em&gt;iterate&lt;/em&gt; over mutile &lt;em&gt;iterable&lt;/em&gt; object at the same time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Return &lt;em&gt;zip&lt;/em&gt; object &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; first_names = ['ram','shyam','ajay','bipin','manoj','alex']
&amp;gt;&amp;gt;&amp;gt; last_names = ['gupta','tiwari','yadav','rawat','desai','khan','raven']
&amp;gt;&amp;gt;&amp;gt; home_town = ['ayodhya','vrindavan','bihar','jhnasi','boston','delhi','lanka']
&amp;gt;&amp;gt;&amp;gt;
&amp;gt;&amp;gt;&amp;gt; detail_iter = zip(first_names, last_names,home_town)
&amp;gt;&amp;gt;&amp;gt; detail_iter
&amp;lt;zip object at 0x000001D28CA41B00&amp;gt;
&amp;gt;&amp;gt;&amp;gt; for detail in detail_iter:
...     print(detail)
...
('ram', 'gupta', 'ayodhya')
('shyam', 'tiwari', 'vrindavan')
('ajay', 'yadav', 'bihar')
('bipin', 'rawat', 'jhnasi')
('manoj', 'desai', 'boston')
('alex', 'khan', 'delhi')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;zip()&lt;/em&gt; function return &lt;em&gt;zip object&lt;/em&gt; which iterate over a list of &lt;em&gt;tuples&lt;/em&gt;  where tuples size is equal to the no. of list passed in the &lt;em&gt;zip()&lt;/em&gt; function&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;also, it will return list of tuples of size equal to the length of (minimum size &lt;em&gt;iterable&lt;/em&gt; among all the &lt;em&gt;iterables&lt;/em&gt; passed in the &lt;em&gt;zip()&lt;/em&gt; function)
i.e 

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;first_names&lt;/em&gt; list has &lt;em&gt;length&lt;/em&gt; of 6&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;last_names&lt;/em&gt; list has &lt;em&gt;length&lt;/em&gt; of 6&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;home_town&lt;/em&gt; list has &lt;em&gt;length&lt;/em&gt; of 7&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, it return list of tuples with list size 6&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;File Iterator&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;It uses a special function -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;open(filename)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is used to iterate over the contents of the file&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;File Content :- 
Details :-
('ram', 'gupta', 'ayodhya')
('shyam', 'tiwari', 'vrindavan')
('ajay', 'yadav', 'bihar')
('bipin', 'rawat', 'jhnasi')
('manoj', 'desai', 'boston')
('alex', 'khan', 'delhi')

Code :-

&amp;gt;&amp;gt;&amp;gt; for line in open("hello.txt"):
...     print(line)
...
Output :-

Details :-

('ram', 'gupta', 'ayodhya')

('shyam', 'tiwari', 'vrindavan')

('ajay', 'yadav', 'bihar')

('bipin', 'rawat', 'jhnasi')

('manoj', 'desai', 'boston')

('alex', 'khan', 'delhi')

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It reads only line at a time&lt;/p&gt;

&lt;p&gt;Now, that we have covered all the 6 &lt;em&gt;iterators&lt;/em&gt;, we now see when to use which iterator&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;When to Use Which Iterator&lt;/strong&gt;?
&lt;/h3&gt;

&lt;p&gt;when we need to :- &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;traverse on a TUPLE (readonly) - &lt;strong&gt;forward iterator&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;traverse on a LIST (readonly) - &lt;strong&gt;forward iterator&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;traverse modify list &lt;strong&gt;inplace&lt;/strong&gt; - &lt;strong&gt;index based iterator&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;traverse mutiple &lt;strong&gt;iterable&lt;/strong&gt; (readonly)   - &lt;strong&gt;parallel iterator&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Comparing Performance of Iterators&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now, we will going to compare performance of &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;(&lt;em&gt;forward iterator, reverse iterator, index based iterator,  enumerate iterator&lt;/em&gt;)&lt;/li&gt;
&lt;li&gt;by iterating a list of size 10000&lt;/li&gt;
&lt;li&gt;comparing the time taken by various iterator &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example :-
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Code :- 
import time
lst = [i for i in range(10000000)]
print("Traversing over list of size 10000000 \n-----------------------------------------------------\n")

start_time = time.time()
for i in lst:
     print("",end="")
end_time = time.time()
print(f"Time take by forward iterator {round(end_time - start_time ,2)} Seconds")

##################################################################

start_time = time.time()
for i in reversed(lst):
     print("",end="")
end_time = time.time()
print(f"Time take by reverse iterator {round(end_time - start_time ,2)} Seconds")


##################################################################

start_time = time.time()
index_based_iter = range(len(lst))
for i in index_based_iter:
     print("",end="")
end_time = time.time()
print(f"Time take by index based iterator {round(end_time - start_time ,2)} Seconds")


##################################################################

start_time = time.time()
index_based_iter = range(len(lst))
for i in index_based_iter:
     print("",end="")
end_time = time.time()
print(f"Time take by enumerate iterator {round(end_time - start_time ,2)} Seconds")


Output :-
Traverseing over list of size 10000000
-----------------------------------------------------

Time take by forward iterator 6.99 Seconds
Time take by reverse iterator 7.45 Seconds
Time take by index based iterator 8.32 Seconds
Time take by enumerate iterator 7.15 Seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we have some to end, hope you all are now fimilar with various types of iterators in python and when to use which iterator.&lt;br&gt;
See you next time , covering some other topic :-)&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
      <category>iterators</category>
    </item>
    <item>
      <title>What is Iterable,iterator in Python?</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Wed, 10 Nov 2021 07:37:59 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/what-is-iterableiterator-in-python-3325</link>
      <guid>https://dev.to/adarshrawat7400/what-is-iterableiterator-in-python-3325</guid>
      <description>&lt;p&gt;First , we have to understand what is itertors, and why it is used?&lt;/p&gt;

&lt;h3&gt;
  
  
  Iterator :-
&lt;/h3&gt;

&lt;p&gt;An iterator is an object that contains a countable number of values, in simple words an iterators stores numbers of values,&lt;br&gt;
through which we can iterated upon (traversing over the values).&lt;/p&gt;

&lt;p&gt;In Python an iterator is an object which implements the iterator protocol, which consist of the methods &lt;strong&gt;&lt;strong&gt;iter&lt;/strong&gt;()&lt;/strong&gt; and &lt;strong&gt;&lt;strong&gt;next&lt;/strong&gt;()&lt;/strong&gt;.&lt;/p&gt;
&lt;h5&gt;
  
  
  Iteratble :-
&lt;/h5&gt;

&lt;p&gt;objects like (strings, list, tuple, sets, dict) are all iterable  (&lt;em&gt;container of values&lt;/em&gt;).&lt;/p&gt;
&lt;h5&gt;
  
  
  Iterator :-
&lt;/h5&gt;

&lt;p&gt;each of above iterable has an &lt;em&gt;iter()&lt;/em&gt; method which can be used to get iterator of that particular object i.e, for list we get list_iterator object , for tuple we get tuple_iterator and so on...&lt;br&gt;
let us understand with an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; student_name = ['ram','shyam','john','harry','ravi']
&amp;gt;&amp;gt;&amp;gt; student_iter = iter(student_name)
&amp;gt;&amp;gt;&amp;gt; student_iter

&amp;lt;list_iterator object at 0x000001E7C37E1F30&amp;gt; # list_iterator object
&amp;gt;&amp;gt;&amp;gt;
&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
ram
&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
shyam
&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
john
&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
harry
&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
ravi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the &lt;em&gt;next(iterable)&lt;/em&gt; we can move over elements in the iterator, Remeber on important in iterator object does not have any exception handler , so if we try to call next() ,when we are on the last element, it will throw an &lt;em&gt;StopIteration&lt;/em&gt; Exception&lt;br&gt;
the last element in the list is 'ravi' and we are currently on ravi, then let's see what happen what happen if we call &lt;em&gt;next()&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
ravi
&amp;gt;&amp;gt;&amp;gt; print(next(student_iter))
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
StopIteration
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are mutiple ways to handle this &lt;em&gt;StopIteration&lt;/em&gt; Exception&lt;br&gt;
let's see each one of them.&lt;/p&gt;

&lt;h5&gt;
  
  
  1. We can use try and except block
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; next(student_iter)
'ravi'
&amp;gt;&amp;gt;&amp;gt; try:
...     print(next(student_iter))
... except StopIteration:
...     print("StopIteration Exception Handled")
...
StopIteration Exception Handled
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we have handled the exception use try and except block,&lt;br&gt;
 it is still a solution to the block , but at the same time , every time we have to use extra lines of code whenever we use &lt;em&gt;next()&lt;/em&gt; on the last element.&lt;/p&gt;

&lt;h5&gt;
  
  
  2. Using for loop
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for student in student_iter:
...     print(student)
...
ram
shyam
john
harry
ravi
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;for loop internally handles the &lt;em&gt;StopIteration&lt;/em&gt; Excetion whenever it &lt;em&gt;next()&lt;/em&gt; called on the last element.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;By Passing Second Argument in &lt;em&gt;next(iterable,sentinel)&lt;/em&gt;
you can think sentinel as the default value return whenever *next * called on the last element.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; student_name = ['ram','shyam','john','harry','ravi']
&amp;gt;&amp;gt;&amp;gt; student_iter = iter(student_name)
&amp;gt;&amp;gt;&amp;gt; next(student_iter,None)
'ram'
&amp;gt;&amp;gt;&amp;gt; next(student_iter,None)
'shyam'
&amp;gt;&amp;gt;&amp;gt; next(student_iter,None)
'john'
&amp;gt;&amp;gt;&amp;gt; next(student_iter,None)
'harry'
&amp;gt;&amp;gt;&amp;gt; next(student_iter,None)
'ravi'
&amp;gt;&amp;gt;&amp;gt; next(student_iter,None)
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see that ,we passed second argument as &lt;em&gt;None&lt;/em&gt; , so when we called next on the last element, it does not throw the &lt;em&gt;StopIteration&lt;/em&gt; Excetion instead it return the &lt;em&gt;sentinel&lt;/em&gt; (default value). In this way we don't don't have to write extra lines of code , only have to pass the second argument.&lt;/p&gt;

&lt;p&gt;That's it for now,&lt;br&gt;
i think it would to enough for now,&lt;br&gt;
I will cover some advance topics about iterator in python in the &lt;br&gt;
next article ,*(types of iterators in python, and which is the most optimal one to use).&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Getting started with Python List Comprehension</title>
      <dc:creator>Adarsh Rawat</dc:creator>
      <pubDate>Tue, 09 Nov 2021 18:11:50 +0000</pubDate>
      <link>https://dev.to/adarshrawat7400/the-right-way-to-use-comprehension-in-python-1ggn</link>
      <guid>https://dev.to/adarshrawat7400/the-right-way-to-use-comprehension-in-python-1ggn</guid>
      <description>&lt;h3&gt;
  
  
  To know the importance of Comprehension in Python, first we have to understand what is Comprehension?
&lt;/h3&gt;

&lt;h2&gt;
  
  
  List Comprehension
&lt;/h2&gt;

&lt;p&gt;List Comprehension is defined as an elegant way to define, create a list in Python and consists of brackets that contains an expression followed by for clause. It is efficient in both computationally and in terms of coding space and time.&lt;/p&gt;

&lt;p&gt;Syntax :- The list comprehension starts with '[' and ']'.&lt;br&gt;
          [ expression for item in list if conditional ]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let's learn it with the help examples&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
Suppose you have generate a list of square over a range of values&lt;br&gt;
first ,you will try to do it with using for loop&lt;/p&gt;

&lt;h4&gt;
  
  
  Using For Loop
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; lst = []
&amp;gt;&amp;gt;&amp;gt; for i in range(1,11):
...     lst.append(i**2)
...
&amp;gt;&amp;gt;&amp;gt; lst
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;do this way will definately do the job but, here we can make use of list comprehension to make this a one liner, let's see&lt;/p&gt;

&lt;h4&gt;
  
  
  Using List comprehension
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; lst = [i**2 for i in range(1,11)]
&amp;gt;&amp;gt;&amp;gt; lst
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in the above , the left most expression will be evaluated and store in the list for every value in the for loop&lt;/p&gt;

&lt;h3&gt;
  
  
  Conditionals in List Comprehension
&lt;/h3&gt;

&lt;p&gt;We can also add conditional statements to the list comprehension. &lt;br&gt;
to store values in the list based wheather the condition is &lt;em&gt;True&lt;/em&gt; or &lt;em&gt;False&lt;/em&gt;,  We can create a list using range(), operators, etc.&lt;br&gt;
let's understand this with an example.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax&lt;/em&gt;: newlist = [expression for item in iterable if condition == True]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;br&gt;
Suppose there are  students in a class and you have to filter the student names based on the performance in the exam, you have a &lt;em&gt;dict&lt;/em&gt; of students with key as there name and value as there marks&lt;br&gt;
So, if a student get marks greater than or equal to 40 then he/she will be included in the list else he/she will not be included.&lt;/p&gt;

&lt;p&gt;First we will try to do it with for loop, then&lt;br&gt;
using list comprehension&lt;/p&gt;

&lt;h4&gt;
  
  
  Using For loop
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
&amp;gt;&amp;gt;&amp;gt; selected_students = []
&amp;gt;&amp;gt;&amp;gt; for student,marks in students.items():
...     if marks &amp;gt;= 40:
...             selected_students.append(student)
...
&amp;gt;&amp;gt;&amp;gt; selected_students
['ram', 'harry', 'john', 'seta', 'philip']
&amp;gt;&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Using List comprehension
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}

&amp;gt;&amp;gt;&amp;gt; selected_students = [student for student,marks in students.items() if marks &amp;gt;= 40]

&amp;gt;&amp;gt;&amp;gt; selected_students
['ram', 'harry', 'john', 'seta', 'philip']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the help of list comprehension we have achived the same task with the same Ridability&lt;/p&gt;

&lt;h3&gt;
  
  
  Nested List Comprehensions
&lt;/h3&gt;

&lt;p&gt;Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. let's understand it with an example.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example 3:-
&lt;/h3&gt;

&lt;p&gt;Suppose you have to generate a matrix where each row contain value from 1 to 4, we will try to do it using for loop then using nestd list comprehensions&lt;/p&gt;

&lt;h4&gt;
  
  
  Using For loop
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; for i in range(3):
...
...     # Append an empty sublist inside the list
...     matrix.append([])
...
...     for j in range(5):
...         matrix[i].append(j)
...
&amp;gt;&amp;gt;&amp;gt; matrix
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Using Nested List Comprehensions
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; matrix = [[i for i in range(5)] for _ in range(3)]
&amp;gt;&amp;gt;&amp;gt; matrix
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Dictionary Comprehension
&lt;/h3&gt;

&lt;p&gt;Just like we use list comprehension ,in the similar way we can also create dictionary in one or two line instead of writing  extra line . we use &lt;em&gt;{&lt;/em&gt; , &lt;em&gt;}&lt;/em&gt; instead of &lt;em&gt;[&lt;/em&gt; , &lt;em&gt;]&lt;/em&gt; braces,&lt;br&gt;
all the other syntax is similar.&lt;br&gt;
let's understand with the example&lt;/p&gt;

&lt;h3&gt;
  
  
  Example 4:-
&lt;/h3&gt;

&lt;p&gt;you have given a lits of fruits and list list of calories corresponding to each of the fruits , now you have to generate a &lt;em&gt;dict&lt;/em&gt; of fruits with &lt;br&gt;
&lt;em&gt;key&lt;/em&gt; as name of the fruit&lt;br&gt;
&lt;em&gt;value&lt;/em&gt; as it calories it has&lt;/p&gt;

&lt;h4&gt;
  
  
  Using For loop
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt;
&amp;gt;&amp;gt;&amp;gt; fruits = ["apple","pineapple","banana","orange","papaya","strawberry","grapes","watermalon"]
&amp;gt;&amp;gt;&amp;gt; calories = [100,141,65,43,120,80,110,200]
&amp;gt;&amp;gt;&amp;gt; fruit_dict = {}
&amp;gt;&amp;gt;&amp;gt; for i in range(len(fruits)):
...     fruit_dict[fruits[i]] = calories[i]
...
&amp;gt;&amp;gt;&amp;gt; fruit_dict
{'apple': 100, 'pineapple': 141, 'banana': 65, 'orange': 43, 'papaya': 120, 'strawberry': 80, 'grapes': 110, 'watermalon': 200}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Using Dict Comprehension
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; fruits = ["apple","pineapple","banana","orange","papaya","strawberry","grapes","watermalon"]
&amp;gt;&amp;gt;&amp;gt; calories = [100,141,65,43,120,80,110,200]
&amp;gt;&amp;gt;&amp;gt; fruits_dict = { fruits[i]:calories[i] for i in range(len(fruits))}
&amp;gt;&amp;gt;&amp;gt; fruits_dict
{'apple': 100, 'pineapple': 141, 'banana': 65, 'orange': 43, 'papaya': 120, 'strawberry': 80, 'grapes': 110, 'watermalon': 200}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use can also Use Condtional Statement in &lt;em&gt;Dict&lt;/em&gt; Comprehension as we used in &lt;em&gt;List&lt;/em&gt; Comprehension &lt;br&gt;
let's take small example&lt;/p&gt;

&lt;h3&gt;
  
  
  Example 5 :-
&lt;/h3&gt;

&lt;p&gt;We will added a student name and his marks based on wheather he/she has got marks greater than or equal to 40 , Refer to example 4.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using For loop
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
&amp;gt;&amp;gt;&amp;gt; selected_students_dict = {}
&amp;gt;&amp;gt;&amp;gt; for student,marks in students.items():
...     if marks &amp;gt;= 40:
...             selected_students_dict[student] = marks
...
&amp;gt;&amp;gt;&amp;gt; selected_students_dict
{'ram': 44, 'harry': 75, 'john': 54, 'seta': 65, 'philip': 56}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Using Dict Comprehension
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
&amp;gt;&amp;gt;&amp;gt; selected_students_dict = {student:marks for student,marks in students.items() if marks &amp;gt;= 40}
&amp;gt;&amp;gt;&amp;gt; selected_students_dict
{'ram': 44, 'harry': 75, 'john': 54, 'seta': 65, 'philip': 56}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have come to an end , the above examples will be enough for you to started with list comprehension , after all it one of the most powerful features of python that every pythonista must now,&lt;br&gt;
i'm added some key takeways below. All the best for your future python explorations :-)&lt;/p&gt;

&lt;h3&gt;
  
  
  Key Takeawys
&lt;/h3&gt;

&lt;p&gt;-&amp;gt; &lt;strong&gt;List comprehension is an elegant way to define and create lists based on existing lists.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;-&amp;gt; &lt;strong&gt;List comprehension is generally more compact and faster than normal functions and loops for creating list.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;-&amp;gt; &lt;strong&gt;we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;-&amp;gt; &lt;strong&gt;every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
