{"id":7020,"date":"2020-07-18T20:14:54","date_gmt":"2020-07-18T14:44:54","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=7020"},"modified":"2023-12-22T19:05:23","modified_gmt":"2023-12-22T13:35:23","slug":"python-data-structures","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/python-data-structures\/","title":{"rendered":"Python Data Structures"},"content":{"rendered":"<p>Python provides several built-in data structures to help us efficiently handle large amounts of data.<\/p>\n<p>Python provides four primary built-in data structures:<\/p>\n<ul>\n<li>List<\/li>\n<li>Tuple<\/li>\n<li>Dictionary<\/li>\n<li>Set<\/li>\n<\/ul>\n<p>Let&#8217;s study each one of them in brief.<\/p>\n<blockquote><p>\nThis tutorial is a part of the free course &#8211; learn python from scratch. Enroll to this free course to learn Python from scratch.\n<\/p><\/blockquote>\n<h2>List<\/h2>\n<p>The list is the most commonly used data structure in Python. It allows us to store elements of different data types in one container.<\/p>\n<p>The contents of a list are enclosed by square brackets, [ ].<\/p>\n<p>Let&#8217;s learn by example code. <\/p>\n<p><code lang='python'><br \/>\nlists = [\"Codeforgeek\", \"Courses\", \"Lessons\", 130]<br \/>\nprint(lists)<\/p>\n<p># Indexing<br \/>\nprint(lists[0])<\/p>\n<p># Length<br \/>\nprint(len(lists))<br \/>\n<\/code><\/p>\n<p>The values in the list are mutable hence we can change them on the fly.<\/p>\n<p><code lang='python'><br \/>\nlists = [\"Codeforgeek\", \"Courses\", \"Lessons\", 130]<br \/>\nprint(lists)<\/p>\n<p># Change the value<br \/>\nlists[3] += 5<br \/>\nprint(lists)<br \/>\n<\/code><\/p>\n<p>This should output the following:<\/p>\n<p><code><br \/>\n['Codeforgeek', 'Courses', 'Lessons', 130]<br \/>\n['Codeforgeek', 'Courses', 'Lessons', 135]<br \/>\n<\/code><\/p>\n<p>We can use the <strong>list()<\/strong> method to cast the existing <strong>range()<\/strong> values in a list. <\/p>\n<p>Here is a simple example.<br \/>\n<code lang='javascript'><br \/>\nnum_seq = range(0, 10)<br \/>\nnum_list = list(num_seq)<br \/>\nprint(num_list)<br \/>\n<\/code><\/p>\n<p>We can also create a nested list i.e lists inside a list.<br \/>\n<code lang='python'><br \/>\nnum = [[1,2],[3,4],[5,6,7,8,9,10],[0.5]]<br \/>\nprint(num[0][1]) #prints 2<br \/>\n<\/code><\/p>\n<p>We can create a 3&#215;3, 4&#215;4, 3&#215;4 lists. Very useful in computer graphics and mathematical problems.<\/p>\n<p>To add a new element in the existing list, we can use the <strong>append()<\/strong> and <strong>insert()<\/strong> method.<\/p>\n<p><code lang='python'><br \/>\nnum_list = [1,2]<br \/>\nnum_list.append(3) # add 3 at the end of the list<br \/>\nprint(num_list)<br \/>\nnum_list.insert(3, 40)  # Inserting 40 at the 3rd index and shifts the index of the list<br \/>\nprint(num_list)<br \/>\n<\/code><\/p>\n<p>The output of the code:<br \/>\n<code><br \/>\n[1, 2, 3]<br \/>\n[1, 2, 3, 40]<br \/>\n<\/code><\/p>\n<p>Similarly, we can remove the element from the list using <strong>pop()<\/strong> or <strong>remove()<\/strong> functions.<\/p>\n<p><code lang='python'><br \/>\nnum_list = [1,2,3,4,5]<br \/>\nnum_list.pop()<br \/>\nprint(num_list)<br \/>\nnum_list.remove(3)  # removes 3 from the list<br \/>\nprint(num_list)<br \/>\n<\/code><\/p>\n<p>The output of the code:<br \/>\n<code><br \/>\n[1, 2, 3, 4]<br \/>\n[1, 2, 4]<br \/>\n<\/code><\/p>\n<p>We can sort the list in the ascending order using <strong>sort()<\/strong> method.<\/p>\n<p><code lang='python'><br \/>\nnum_list = [20, 40, 10, 50.4, 30, 100, 5]<br \/>\nnum_list.sort()<br \/>\nprint(num_list)<br \/>\n<\/code><br \/>\nThe output of the code:<br \/>\n<code><br \/>\n[5, 10, 20, 30, 40, 50.4, 100]<br \/>\n<\/code><\/p>\n<p>Let&#8217;s study the next data structure i.e tuples.<\/p>\n<h2>Tuple<\/h2>\n<p>A tuple is a list that is immutable i.e once it is declared, the value cannot be changed. However, a tuple can contain a list, and values in the list can be changed.<\/p>\n<p>Let&#8217;s learn by example.<br \/>\n<code lang='python'><br \/>\nnum_lists = (1,2,3,4,5,6,7,8,9,10)<br \/>\nprint(num_lists)<br \/>\nprint(num_lists[0])<br \/>\nprint(len(num_lists))<br \/>\n<\/code><br \/>\nIf you observe we initialized the tuple using <strong>( )<\/strong> instead of <strong>[ ]<\/strong> as we do on the list.<\/p>\n<p>Since tuples are immutable, we can&#8217;t change the value inside the tuple. However, we can use nested tuple and use lists inside the tuple to change the values if required.<\/p>\n<p>Let&#8217;s learn by example.<br \/>\n<code lang='python'><br \/>\nnum_lists=([1,2,3],[4,5,6])<br \/>\nprint(num_lists[0])<br \/>\n# change value of list inside the tuple<br \/>\nnum_lists[0][0] += 5<br \/>\nprint(num_lists)<br \/>\n<\/code><\/p>\n<p>The output of the code.<br \/>\n<code><br \/>\n[1, 2, 3]<br \/>\n([6, 2, 3], [4, 5, 6])<br \/>\n<\/code><\/p>\n<p>You can search in the tuples.<br \/>\n<code lang='python'><br \/>\ncities = (\"London\", \"Paris\", \"Los Angeles\", \"Tokyo\")<br \/>\nprint(\"London\" in cities) # True<br \/>\nprint(\"Mumbai\" in cities) # False<br \/>\n<\/code><\/p>\n<p>Let&#8217;s learn the next data structure i.e Dictionaries. <\/p>\n<h2>Dictionary<\/h2>\n<p>A dictionary stores data in key-value pairs, where each unique key is an index that holds the value associated with it. If you are familiar with JSON data type in JavaScript then dictionary data type is similar to that.<\/p>\n<p>Dictionary data type is initialized using key:value format inside curly brackets { }.<\/p>\n<p>Let&#8217;s learn by example.<br \/>\n<code lang='python'><br \/>\nuserId = {<br \/>\n    \"100\": \"Shahid\",<br \/>\n    \"120\": \"John\",<br \/>\n    \"130\": \"Mary\"<br \/>\n}<\/p>\n<p>print(userId)<br \/>\nprint(len(userId))<br \/>\nprint(userId[\"100\"])<br \/>\n<\/code><\/p>\n<p>The output of the code:<br \/>\n<code><br \/>\n{'100': 'Shahid', '130': 'Mary', '120': 'John'}<br \/>\n3<br \/>\nShahid<br \/>\n<\/code><\/p>\n<p>Observe the third <strong>print()<\/strong> statement. Using the key, we can retrieve the data from the dictionary. <\/p>\n<p>It&#8217;s so useful in building a large set of applications.<\/p>\n<p>You can also access the values using <strong>get()<\/strong> method. Pass the key in the get() method to retrieve values.<\/p>\n<p>To add\/update the new\/existing element in the existing dictionary, we can use the following code.<br \/>\n<code lang='python'><br \/>\nuserId = {<br \/>\n    \"100\": \"Shahid\",<br \/>\n    \"120\": \"John\",<br \/>\n    \"130\": \"Mary\"<br \/>\n}<\/p>\n<p>userId[\"150\"] = \"Wick\" # add new entry<br \/>\nuserId[\"100\"] = \"Shahid Shaikh\"<br \/>\nprint(userId)<br \/>\n<\/code><\/p>\n<p>The output of the code above.<br \/>\n<code><br \/>\n{'100': 'Shahid Shaikh', '130': 'Mary', '120': 'John', '150': 'Wick'}<br \/>\n<\/code><\/p>\n<p>To remove the values from the dictionary, we can use the <strong>pop()<\/strong> or <strong>popitem()<\/strong> method.<\/p>\n<p><code lang='python'><br \/>\nuserId = {<br \/>\n    \"100\": \"Shahid\",<br \/>\n    \"120\": \"John\",<br \/>\n    \"130\": \"Mary\"<br \/>\n}<\/p>\n<p>removedItem = userId.pop(\"100\")<br \/>\nlastItem = userId.popitem()<br \/>\nprint(removedItem)<br \/>\nprint(lastItem)<br \/>\n<\/code><\/p>\n<p>We can check whether the key exists or not using the <strong>in<\/strong> operator.<br \/>\n<code lang='python'><br \/>\nuserId = {<br \/>\n    \"100\": \"Shahid\",<br \/>\n    \"120\": \"John\",<br \/>\n    \"130\": \"Mary\"<br \/>\n}<\/p>\n<p>print(\"100\" in userId) # True<br \/>\nprint(\"500\" in userId) # False<br \/>\n<\/code><br \/>\nLet&#8217;s learn our last data structure i.e sets.<\/p>\n<h2>Set<\/h2>\n<p>A Set is a simple data structure that contains non-duplicate unordered items. Sets do not allow duplicate values and there is no way to fetch the values from a Set without iterating through it.<\/p>\n<p>Let&#8217;s learn by example.<br \/>\n<code lang='python'><br \/>\ntest_set = {1,2,3,\"Shahid\", (1.5,2.5)}<br \/>\nprint(test_set)<br \/>\nprint(len(test_set))  # Length of the set<br \/>\n<\/code><br \/>\nA Set also holds values inside the curly brackets similar to dictionaries except there is no key:value pair.<\/p>\n<p>To add a new element or elements in the Set, we can use <strong>add()<\/strong> or <strong>update()<\/strong> methods.<\/p>\n<p><code lang='python'><br \/>\nnew_set = {1,2,3}<br \/>\nnew_set.add(10)<br \/>\nprint(new_set)<\/p>\n<p>new_set.update([20, 30, 40])<br \/>\nprint(new_set)<br \/>\n<\/code><\/p>\n<p>Similarly, we can remove elements from Set as well. We can use the <strong>remove()<\/strong> method.<\/p>\n<p><code lang='python'><br \/>\nnew_set = {1,2,3,4,5}<br \/>\nprint(new_set)<\/p>\n<p>new_set.remove(5)<br \/>\nprint(new_set)<br \/>\n<\/code><\/p>\n<p>We can iterate through the Set as well.<\/p>\n<p><code lang='python'><br \/>\nnew_set = {1,2,3,4,5}<\/p>\n<p>for set_value in new_set:<br \/>\n    print(set_value)<br \/>\n<\/code><\/p>\n<p>I highly recommend you to deep dive more in the data structures in Python. It&#8217;s important and crucial for interviews in FAANG companies as well as it is going to help you become a better software developer.<\/p>\n<blockquote><p>\nThis tutorial is a part of the free course &#8211; learn python from scratch. Enroll to this free course to learn Python from scratch.\n<\/p><\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>Python provides several built-in data structures to help us efficiently handle large amounts of data. Python provides four primary built-in data structures: List Tuple Dictionary Set Let&#8217;s study each one of them in brief. This tutorial is a part of the free course &#8211; learn python from scratch. Enroll to this free course to learn [&hellip;]<\/p>\n","protected":false},"author":69,"featured_media":7032,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[134,18],"tags":[],"class_list":["post-7020","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-tutorial"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures.jpg",1500,750,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures-150x150.jpg",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures-300x150.jpg",300,150,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures-768x384.jpg",768,384,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures-1024x512.jpg",1024,512,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures.jpg",1500,750,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/Python-Data-Structures.jpg",1500,750,false]},"uagb_author_info":{"display_name":"Pankaj Kumar","author_link":"https:\/\/codeforgeek.com\/author\/pankaj\/"},"uagb_comment_info":0,"uagb_excerpt":"Python provides several built-in data structures to help us efficiently handle large amounts of data. Python provides four primary built-in data structures: List Tuple Dictionary Set Let&#8217;s study each one of them in brief. This tutorial is a part of the free course &#8211; learn python from scratch. Enroll to this free course to learn&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/7020","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/69"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=7020"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/7020\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/7032"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=7020"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=7020"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=7020"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}