Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Swap List Elements in Python?

#1
How to Swap List Elements in Python?

<div><h2>Problem Formulation</h2>
<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>
<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>
<p><strong>Examples:</strong></p>
<ul>
<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>
<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>
<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>
</ul>
<h2>Method 1: Multiple Assignment</h2>
<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>
<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']
i, j = 0, 2 # Swap index i=0 with index j=2
lst[i], lst[j] = lst[j], lst[i] print(lst)
# ['carl', 'bob', 'alice']</pre>
<p>The highlighted line works as follows: </p>
<ul>
<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>
<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>
</ul>
<p>To help you better understand this code snippet, I’ve 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>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<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>
</div>
</figure>
<h2>Method 2: Swap Two Elements by Value Using indexof()</h2>
<p>Let’s quickly discuss a variant of this problem whereby you want to swap two elements but you don’t know their indices yet. </p>
<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>
<p>The latter part, i.e., swapping the list elements, remains the same. The main difference is highlighted in the following code snippet:</p>
<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']
x, y = 'alice', 'carl' # Get indices i and j associated with elements x and y
i, j = lst.index(x), lst.index(y) # Swap element at index i with element at index j
lst[i], lst[j] = lst[j], lst[i] print(lst)
# ['carl', 'bob', 'alice']
</pre>
<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>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" 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>
<p>Feel free to also watch the following quick explainer video:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<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>
</div>
</figure>
<h2>Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img 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/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
</div>
<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 “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p>
<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’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>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<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>
<li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<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>
<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>
</ul>
<p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<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>
</div>


https://www.sickgaming.net/blog/2022/03/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016