{"id":1626,"date":"2024-02-11T22:15:39","date_gmt":"2024-02-11T16:45:39","guid":{"rendered":"https:\/\/geekpython.in\/?p=1626"},"modified":"2024-03-01T17:03:07","modified_gmt":"2024-03-01T11:33:07","slug":"python-getitem-method","status":"publish","type":"post","link":"https:\/\/geekpython.in\/python-getitem-method","title":{"rendered":"Python&#8217;s __getitem__ Method: Accessing Custom Data"},"content":{"rendered":"\n<p>You must have used the square bracket notation (<code>[]<\/code>) method to access the items from the collection such as list, tuple, or dictionary.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >my_lst = [\"Sachin\", \"Rishu\", \"Yashwant\"]\n\nitem = my_lst[0]\nprint(item)<\/pre><\/div>\n\n\n\n<p>The first element of the list (<code>my_lst<\/code>) is accessed using the square bracket notation method (<code>my_list[0]<\/code>) and printed in the above code.<\/p>\n\n\n\n<p>But do you know how this happened? When <code>my_lst[0]<\/code> is evaluated, Python calls the list&#8217;s <code>__getitem__<\/code> method.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:4 decode:true \" >my_lst = [\"Sachin\", \"Rishu\", \"Yashwant\"]\n\n# item = my_lst[0]\nitem = my_lst.__getitem__(0)\nprint(item)<\/pre><\/div>\n\n\n\n<p>This is the same as the above code, but Python handles it behind the scenes, and you will get the same result, which is the first element of <code>my_lst<\/code>.<\/p>\n\n\n\n<p>You may be wondering <strong>what the <code>__getitem__<\/code> method is and where it should be used<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>The __getitem<\/strong>__ Method<\/h2>\n\n\n\n<p>The <code><strong>__getitem__<\/strong><\/code> method is usually implemented within Python classes to make the object of that class work with the square bracket (<code>[]<\/code>) notation.<\/p>\n\n\n\n<p>To put it simply, you can use square bracket notation on the class&#8217;s objects in the same way that you would with Python&#8217;s built-in methods.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >my_lst = [\"Sachin\", \"Rishu\", \"Yashwant\"]\n\nitem = my_lst[0]\nprint(item)\n\n# Using [] operator on class instance w\/o __getitem__ method\nclass Names:\n    def __init__(self):\n        pass\n\nfriends = Names()\nresult = friends[\"Sachin\", \"Rishu\", \"Yashwant\"]<\/pre><\/div>\n\n\n\n<p>In the first block of code, the <code>[]<\/code> operator is used to access a list item.<\/p>\n\n\n\n<p>In the second block of code, a class (<code>Names<\/code>) is defined without implementing the <code>__getitem__<\/code> method. The <code>[]<\/code> operator is applied to the class&#8217;s object (<code>friends<\/code>).<\/p>\n\n\n\n<p>What happens when you run the above code? The first block of code will work because the <code>[]<\/code> operator is used on the built-in datatype, but the second block of code will fail because the class does not have the <code>__getitem__<\/code> method to perform this functionality on the object.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >Sachin\nTraceback (most recent call last):\n  ....\n    result = friends[\"Sachin\", \"Rishu\", \"Yashwant\"]\nTypeError: 'Names' object is not subscriptable<\/pre><\/div>\n\n\n\n<p>If you implement the <code>__getitem__<\/code> method within the class, the above code will work just fine.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:9-10 decode:true \" >...\n\n# Using [] operator on class instance with __getitem__ method\nclass Names:\n    def __init__(self):\n        pass\n    \n    # Implemented the __getitem__ method\n    def __getitem__(self, name):\n        print(f'Name: {name[0]}')\n\nfriends = Names()\nresult = friends[\"Sachin\", \"Rishu\", \"Yashwant\"]<\/pre><\/div>\n\n\n\n<p>When you run this code, there will be no errors, and the first element will be printed as specified by the <code>__getitem__<\/code> method.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >Sachin\nName: Sachin<\/pre><\/div>\n\n\n\n<p>You can see the difference after implementing the <code>__getitem__<\/code> method, the object (<code>friends<\/code>) is now allowed to access values using the <code>[]<\/code> operator.<\/p>\n\n\n\n<p>Now how does <code>__getitem__<\/code> work? First, let&#8217;s understand the syntax of this magic method.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax<\/h3>\n\n\n\n<p><code>__getitem__(self, key)<\/code><\/p>\n\n\n\n<p>The <code>__getitem__<\/code> method typically accepts a single argument besides <code>self<\/code>, which is commonly referred to as <code>key<\/code> when dealing with mappings like dictionaries. This argument represents the index or key used to access the value in the object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<p>Assume you have a large number of entries with employee names and you want to retrieve the first name of each employee from them.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >class EmployeeFirstName:\n    def __init__(self, file):\n        self.file = file\n\n    def __getitem__(self, name):\n        with open(self.file, \"r\") as f:\n            result = f.readlines()\n            first_name = [fname.split()[name] for fname in result]\n            return first_name\n\n\nemployee = EmployeeFirstName(\"employee_data\")\nprint(\"List of Employees First Names:\")\nprint(employee[0])<\/pre><\/div>\n\n\n\n<p>The class accepts a <code>file<\/code> parameter, and the <code>__getitem__<\/code> method opens and reads the file line by line, iterating through each line and splitting it into words with the <code>split()<\/code> method before selecting the word at the index <code>name<\/code>.<\/p>\n\n\n\n<p>When the class (<code>EmployeeFirstName<\/code>) is instantiated, it receives a file (<code>employee_data<\/code>), and the square bracket notation (<code>[]<\/code>) is used on the instance (<code>employee[0]<\/code>) to access the values at the <code>0th<\/code> index from the file.<\/p>\n\n\n\n<p>When you run the code, you will get a list of the employees&#8217; first names from the file.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >List of Employees First Names:\n['John', 'Cindy', 'Jacob', 'Priya', 'Ivan', 'Ji-min', 'Maria', 'Alexander', 'Li', 'Emily']<\/pre><\/div>\n\n\n\n<p>You were able to access the values because the <code>__getitem__<\/code> method was implemented in the class and you can see that the <code>name<\/code> argument is used as a key to access values based on the index.<\/p>\n\n\n\n<p>If you change the value of the name to <code>1<\/code>, you will get the employees&#8217; last names.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:3 decode:true \" >employee = EmployeeFirstName(\"employee_data\")\nprint(\"List of Employees Last Names:\")\nprint(employee[1])<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >List of Employees Last Names:\n['Doe', 'Carl', 'Dawson', 'Patel', 'Petrov', 'Kim', 'Garcia', 'Sokolov', 'Wei', 'Johnson']<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>The <code>__getitem__<\/code> method is implemented within a Python class, allowing the class object to use square bracket notation (<code>[]<\/code>) in the same way that built-in methods do.<\/p>\n\n\n\n<p>You can&#8217;t use the <code>[]<\/code> operator on the instance without implementing the <code>__getitem__<\/code> method.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/implement-getitem-setitem-and-delitem-in-python\">How to implement getitem, setitem, and delitem in Python classes<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/map-function-in-python\">How to use map() in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/pickle-module-in-python\">Serialize and deserialize Python objects using the pickle module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/understanding-if-__name__-__main__-in-python-programs\">Why if __name__ == \u2018__main__\u2019 is used in Python programs<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python\">Create a WebSocket server and client in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You must have used the square bracket notation ([]) method to access the items from the collection such as list, tuple, or dictionary. The first element of the list (my_lst) is accessed using the square bracket notation method (my_list[0]) and printed in the above code. But do you know how this happened? When my_lst[0] is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1628,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[31],"class_list":["post-1626","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1626","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1626"}],"version-history":[{"count":8,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1626\/revisions"}],"predecessor-version":[{"id":1635,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1626\/revisions\/1635"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1628"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1626"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1626"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1626"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}