{"id":123123,"date":"2022-03-21T20:41:53","date_gmt":"2022-03-21T20:41:53","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=254159"},"modified":"2022-03-21T20:41:53","modified_gmt":"2022-03-21T20:41:53","slug":"how-to-swap-list-elements-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/03\/21\/how-to-swap-list-elements-in-python\/","title":{"rendered":"How to Swap List Elements in Python?"},"content":{"rendered":"<h2>Problem Formulation<\/h2>\n<p>Given a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\">list<\/a> of <a href=\"https:\/\/blog.finxter.com\/python-len\/\" data-type=\"post\" data-id=\"22386\" target=\"_blank\" rel=\"noreferrer noopener\">size<\/a> <code>n<\/code> and two indices <code>i,j &lt; n<\/code>. <\/p>\n<p>Swap the element at index <code>i<\/code> with the element at index <code>j<\/code>, so that the element <code>list[i]<\/code> is now at position <code>j<\/code> and the original element <code>list[j]<\/code> is now at position <code>i<\/code>. <\/p>\n<p><strong>Examples:<\/strong><\/p>\n<ul>\n<li>Swapping indices <code>0<\/code> and <code>2<\/code> in list <code>[<strong>1<\/strong>, 2, <strong>3<\/strong>]<\/code> modifies the list to <code>[<strong>3<\/strong>, 2, <strong>1<\/strong>]<\/code>.<\/li>\n<li>Swapping indices <code>1<\/code> and <code>2<\/code> in list <code>[1, <strong>2<\/strong>, <strong>3<\/strong>]<\/code> modifies the list to <code>[1, <strong>3<\/strong>, <strong>2<\/strong>]<\/code>.<\/li>\n<li>Swapping indices <code>1<\/code> and <code>3<\/code> in list <code>['alice', <strong>'bob'<\/strong>, 'carl', <strong>'denis'<\/strong>]<\/code> modifies the list to <code><code>['alice', <strong>'denis'<\/strong>, 'carl', <strong>'bob'<\/strong>]<\/code><\/code>.<\/li>\n<\/ul>\n<h2>Method 1: Multiple Assignment<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">To swap two list elements by index <code>i<\/code> and <code>j<\/code>, use the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-slice-assignment\/\" data-type=\"post\" data-id=\"1942\" target=\"_blank\">multiple assignment<\/a> expression <code>lst[i], lst[j] = lst[j], lst[i]<\/code> that assigns the element at index <code>i<\/code> to index <code>j<\/code> and vice versa.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = ['alice', 'bob', 'carl']\ni, j = 0, 2 # Swap index i=0 with index j=2\nlst[i], lst[j] = lst[j], lst[i] print(lst)\n# ['carl', 'bob', 'alice']<\/pre>\n<p>The highlighted line works as follows: <\/p>\n<ul>\n<li>First, it obtains the elements at positions <code>j<\/code> and <code>i<\/code> by running the right-hand side of the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-operators-overview\/\" data-type=\"post\" data-id=\"30277\" target=\"_blank\">assignment<\/a> operation. <\/li>\n<li>Second, it assigns the obtained elements in one go to the inverse indices <code>i<\/code> and <code>j<\/code> (see left-hand side of the assignment operation).<\/li>\n<\/ul>\n<p>To help you better understand this code snippet, I\u2019ve recorded a quick video that shows you how the generalization of multiple assignment, i.e., <em>slice assignment<\/em>, works as a <a rel=\"noreferrer noopener\" href=\"https:\/\/pythononeliners.com\/\" target=\"_blank\">Python One-Liner<\/a>:<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Python One-Liners - Trick 6 - Slice Assignment to Clean Corrupted Browser Data\" width=\"780\" height=\"439\" src=\"https:\/\/www.youtube.com\/embed\/6LU_Aiq3lT4?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div>\n<\/figure>\n<h2>Method 2: Swap Two Elements by Value Using indexof()<\/h2>\n<p>Let&#8217;s quickly discuss a variant of this problem whereby you want to swap two elements but you don&#8217;t know their indices yet. <\/p>\n<p class=\"has-global-color-8-background-color has-background\">To swap two list elements <code>x<\/code> and <code>y<\/code> by value, get the index of their first occurrences using the <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-index\/\" data-type=\"post\" data-id=\"7096\" target=\"_blank\">list.index(x)<\/a><\/code> and <code>list.index(y)<\/code> methods and assign the result to variables <code>i<\/code> and <code>j<\/code>, respectively. Then apply the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-slice-assignment\/\" data-type=\"post\" data-id=\"1942\" target=\"_blank\">multiple assignment<\/a> expression <code>lst[i], lst[j] = lst[j], lst[i]<\/code> to swap the elements.<\/p>\n<p>The latter part, i.e., swapping the list elements, remains the same. The main difference is highlighted in the following code snippet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = ['alice', 'bob', 'carl']\nx, y = 'alice', 'carl' # Get indices i and j associated with elements x and y\ni, j = lst.index(x), lst.index(y) # Swap element at index i with element at index j\nlst[i], lst[j] = lst[j], lst[i] print(lst)\n# ['carl', 'bob', 'alice']\n<\/pre>\n<p> Do you need a quick refresher on the <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list-index\/\" target=\"_blank\">list.index()<\/a><\/code> method?<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Background<\/strong>: The <code>list.index(value)<\/code> method returns the index of the <code>value<\/code> argument in the <code>list<\/code>. You can use optional <code>start<\/code> and <code>stop<\/code> arguments to limit the index range where to search for the value in the list. If the value is not in the list, the method throws a <code>ValueError<\/code>.<\/p>\n<p>Feel free to also watch the following quick explainer video:<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Python List index() - Everything You Need to Know (and some more)\" width=\"780\" height=\"439\" src=\"https:\/\/www.youtube.com\/embed\/A-j5ngl4mzc?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe>\n<\/div>\n<\/figure>\n<h2>Python One-Liners Book: Master the Single Line First!<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<\/div>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: <strong><em>concise statements of useful functionality packed into a single line of code. <\/em><\/strong>You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. <\/p>\n<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts <\/em><\/strong>and<strong><em> boost your coding and analytical skills<\/em><\/strong>. You&#8217;ll learn about advanced Python features such as <em><strong>list comprehension<\/strong><\/em>, <strong><em>slicing<\/em><\/strong>, <strong><em>lambda functions<\/em><\/strong>, <strong><em>regular expressions<\/em><\/strong>, <strong><em>map <\/em><\/strong>and <strong><em>reduce <\/em><\/strong>functions, and <strong><em>slice assignments<\/em><\/strong>. <\/p>\n<p>You&#8217;ll also learn how to:<\/p>\n<ul>\n<li>Leverage data structures to <strong>solve real-world problems<\/strong>, like using Boolean indexing to find cities with above-average pollution<\/li>\n<li>Use <strong>NumPy basics<\/strong> such as <em>array<\/em>, <em>shape<\/em>, <em>axis<\/em>, <em>type<\/em>, <em>broadcasting<\/em>, <em>advanced indexing<\/em>, <em>slicing<\/em>, <em>sorting<\/em>, <em>searching<\/em>, <em>aggregating<\/em>, and <em>statistics<\/em><\/li>\n<li>Calculate basic <strong>statistics <\/strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning<\/li>\n<li>Create more <strong>advanced regular expressions<\/strong> using <em>grouping <\/em>and <em>named groups<\/em>, <em>negative lookaheads<\/em>, <em>escaped characters<\/em>, <em>whitespaces, character sets<\/em> (and <em>negative characters sets<\/em>), and <em>greedy\/nongreedy operators<\/em><\/li>\n<li>Understand a wide range of <strong>computer science topics<\/strong>, including <em>anagrams<\/em>, <em>palindromes<\/em>, <em>supersets<\/em>, <em>permutations<\/em>, <em>factorials<\/em>, <em>prime numbers<\/em>, <em>Fibonacci <\/em>numbers, <em>obfuscation<\/em>, <em>searching<\/em>, and <em>algorithmic sorting<\/em><\/li>\n<\/ul>\n<p>By the end of the book, you&#8217;ll know how to <strong><em>write Python at its most refined<\/em><\/strong>, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners on Amazon!!<\/em><\/a><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem Formulation Given a list of size n and two indices i,j &lt; n. Swap the element at index i with the element at index j, so that the element list[i] is now at position j and the original element list[j] is now at position i. Examples: Swapping indices 0 and 2 in list [1, [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-123123","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123123","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=123123"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123123\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=123123"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=123123"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=123123"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}