{"id":80191,"date":"2021-01-29T09:00:03","date_gmt":"2021-01-29T03:30:03","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=80191"},"modified":"2021-01-29T09:00:03","modified_gmt":"2021-01-29T03:30:03","slug":"python-modules-types-syntax-examples","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/","title":{"rendered":"Python Modules &#8211; Types, Syntax and Examples"},"content":{"rendered":"<p>In this article, we will have a brief glance on types of python modules- Counter, Defaultdict, Ordereddict, Namedtuple.<\/p>\n<p>Here, we will have a quick and basic understanding of what these modules are, what&#8217;s their function.<\/p>\n<h2>Types of Python Modules<\/h2>\n<h3>1. Counter Module in Python<\/h3>\n<p>A counter tool in python provides support from the tallies.class collections. The general Counter([iterable-or-mapping]).<\/p>\n<p>A counter module works on the mutable objects in a python code. It selects the key elements of the dictionary and hence compares them with the rest of the elements. The value which is always allowed, is integral values inclusive of the negative values.<\/p>\n<p><strong>Python Counter Module Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">c = ('a=5', 'b=3', 'c=1', 'd=-1')\nprint(c)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">a=5&#8242;, &#8216;b=3&#8217;, &#8216;c=1&#8217;, &#8216;d=-1&#8217;<\/div>\n<h4>most_common([n])<\/h4>\n<p>As the name suggests, it returns a list of the \u2018n\u2019 numbers which are the most common elements and hence their counts. If (n) includes in the most common list then it is taken as one in a runtime.<\/p>\n<h4>The subtract([iterable-or-mapping])<\/h4>\n<p>This removes the unwanted element from the list of arrays. It simply waves a wand of magic to the elements which are used less in the array.<\/p>\n<p><strong>fromkeys(iterable):<\/strong> This method helps the coder extract the values of iterable objects from the domainial mutable lists.<br \/>\nupdate([iterable-or-mapping])<\/p>\n<p>This literal variably updates the already present key values in a code, as instructed by the coder.<\/p>\n<h3>Defaultdict Module in Python<\/h3>\n<p>Defaultdict in python is yet a very important module.<\/p>\n<p>It imports the immutable library modules in the main source code, with the help of which it acts as a user interface code, in extracting out bulk data in runtime.<\/p>\n<p><strong>Example of Python Defaultdict Module<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Dict = {1: 'Tech', 2: 'Vidvan', 3: 'Site'}  \nprint(\"YOURDICTIONARYIS: \")  \nprint(Dict) \nprint(Dict[1]) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">YOURDICTIONARYIS:<br \/>\n{1: &#8216;Tech&#8217;, 2: &#8216;Vidvan&#8217;, 3: &#8216;Site&#8217;}<br \/>\nTech<br \/>\n&gt;&gt;&gt;<\/div>\n<p><strong>Defaultdict as class:<\/strong><br \/>\nIt acts as a container to the immutable objects in the source code. It is also a subclass of dictionary-like objects also. The main noticeable feature of defaultdict is that it never raises an exception error, until provided with a syntax error.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">default.dic(\u201center\u201d)\n<\/pre>\n<h4>defaultdict(default_factory)<\/h4>\n<p><strong>default_factory:<\/strong> It is a basic function, which returns the factory function from the import module to the main source code in run time.<\/p>\n<h4>Inner Working of defaultdict<\/h4>\n<p>Defaultdict generally parses the internal elements from the list of immutable arrays collected by the coder in runtime of the code.<\/p>\n<p><strong>Python Defaultdict Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict \nd = defaultdict(lambda: \"NotPresent\") \nd[\"optionone\"] = 20099\nd[\"optiontwo\"] = 20090\nprint(d[\"optionone\"]) \nprint(d[\"option2\"]) \nprint(d[\"option1\"])\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">20099<br \/>\nNotPresent<br \/>\nNotPresent<br \/>\n&gt;&gt;&gt;NotPresent<\/div>\n<p><strong>__missing__():<\/strong> This is a sub -function of the library class, which searches for the missing variable as instructed by the coder in the whole program in one go.<\/p>\n<p><strong>Code :<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from collections import defaultdict \noneno = defaultdict(int) \na = [1, 2, 3, 4, 5, 4, 1, 2]\nfor techno in a: \n    oneno[techno] += 1   \nprint(oneno) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">defaultdict(&lt;class &#8216;int&#8217;&gt;, {1: 2, 2: 4, 3: 1, 4: 2})<\/div>\n<h3>Named Tuple in Python<\/h3>\n<p>The NamedTuple is yet another interesting class, under the collections module.<\/p>\n<p>As the dictionary type objects, it contains keys that are specifically linked with some elements.<\/p>\n<p><strong>Syntax of Python Named Tuple:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Collections.namedtuple<\/pre>\n<h4>Conversion Procedures of NamedTuple<\/h4>\n<p>It converts the inner parsed objects to its library, and then proceeds the same way as the outer loop only.<\/p>\n<h4>classmethod somenamedtuple._make(iterable)<\/h4>\n<p>Class method that makes a new instance from an existing sequence or iterable within the runtime for user specific codes.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&gt;&gt;&gt; \n#thisistech1 = [100,99]\n\n#thisistech(x=89, y=89)\nprint (34)\n\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">34<\/div>\n<p><strong>getattr():<\/strong> To retrieve a field whose name is saved in a string, use the getattr() function within the runtime:<\/p>\n<p><strong>Syntax of getattr in Python:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">getattr(p, 'x')<\/pre>\n<h4>Subclassing Namedtuples<\/h4>\n<p>Namedtuple can be parsed as a subclass in any code which is executed in the runtime. This is also done by checking each element of the namedtuple with the library, and then printing the output.<\/p>\n<h3>OrderedDict Module in Python<\/h3>\n<p>As the name suggests it displays the variables in the form of an ordered dictionary on python code.<\/p>\n<p>In ordered dict the list elements are mutable, i.e they can be changed whenever the user wants. This makes ordereddict frequently used and a better module than any other previous modules.<\/p>\n<p><strong>Example of OrderedDict Module in Python<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">OrderedDict() \nonumber['p'] = 1\npnumber['q'] = 2\nqnumber['r'] = 3\nanumber['s'] = 4\n  \nfor key, value in number_.items(): \n    print(key, value) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">error<\/div>\n<p><strong>Deletion and Re-Inserting:<\/strong> This deletes after elements that are parsed by the user. This can be alternatively done by the for loop as well.<\/p>\n<p>The deleting of the key elements is however not possible in this case because of its high shallow copying property which is inbuilt. However, an effective change can surely be seen in some codes by doing the changes in the main code.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">range=1,2,3,4,5,6,7\nfor key, value in range: \n    print(key, value)  \nprint(\"After deleting the value is:\") \nnumbertwo.pop('c') \nfor key, value in od.items(): \n    print(key, value)   \nprint(\"After re-inserting the value is\") \nnumberone['def'] = 3\nfor key, value in od.items(): \n    print(key, value) \n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">error<\/div>\n<h2>Conclusion<\/h2>\n<p>In this article, we\u2019ve had a brief description of the types of modules in Python, their functions and usage.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will have a brief glance on types of python modules- Counter, Defaultdict, Ordereddict, Namedtuple. Here, we will have a quick and basic understanding of what these modules are, what&#8217;s their&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":80193,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[3355,3356,2996,3357],"class_list":["post-80191","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-counter-module-in-python","tag-defaultdict-in-python","tag-modules-in-python","tag-python-modules"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Modules - Types, Syntax and Examples - TechVidvan<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Modules - Types, Syntax and Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"In this article, we will have a brief glance on types of python modules- Counter, Defaultdict, Ordereddict, Namedtuple. Here, we will have a quick and basic understanding of what these modules are, what&#8217;s their&#046;&#046;&#046;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-01-29T03:30:03+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Modules-TV.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Modules - Types, Syntax and Examples - TechVidvan","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/","og_locale":"en_US","og_type":"article","og_title":"Python Modules - Types, Syntax and Examples - TechVidvan","og_description":"In this article, we will have a brief glance on types of python modules- Counter, Defaultdict, Ordereddict, Namedtuple. Here, we will have a quick and basic understanding of what these modules are, what&#8217;s their&#46;&#46;&#46;","og_url":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-01-29T03:30:03+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Modules-TV.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Modules &#8211; Types, Syntax and Examples","datePublished":"2021-01-29T03:30:03+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/"},"wordCount":727,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Modules-TV.jpg","keywords":["Counter Module in python","defaultdict in python","Modules in Python","Python Modules"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/","url":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/","name":"Python Modules - Types, Syntax and Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Modules-TV.jpg","datePublished":"2021-01-29T03:30:03+00:00","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Modules-TV.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/01\/Python-Modules-TV.jpg","width":1200,"height":628,"caption":"Python Modules"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-modules-types-syntax-examples\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Modules &#8211; Types, Syntax and Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80191","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=80191"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80191\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/80193"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=80191"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=80191"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=80191"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}