Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List reverse()

#1
Python List reverse()

<div><p>This tutorial shows you everything you need to know to help you master the essential <code>reverse()</code> method of the most fundamental container data type in the Python programming language.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python List reverse()" width="1400" height="788" src="https://www.youtube.com/embed/H9ri4UVg6-E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Definition and Usage</strong>:</p>
<p><strong>The <code>list.reverse()</code> reverses the order of the elements in the <code>list</code>. If you want to create a new list with reversed elements, use slicing with negative step size <code>list[::-1]</code>. </strong></p>
<p>Here’s a short example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [1, 2, 3, 4]
>>> lst.reverse()
>>> lst
[4, 3, 2, 1]</pre>
<p>In the first line of the example, you create the list <code>lst</code>. You then reverse the order of the elements in the list and print it to the shell.</p>
<p><strong>Code Puzzle — Try It Yourself:</strong></p>
<p>Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?</p>
<p> <iframe src="https://repl.it/repls/MadeupConsiderableErrors?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="600px" frameborder="no"></iframe> </p>
<p><a href="https://app.finxter.com/learn/computer/science/564" target="_blank" rel="noreferrer noopener">You can also solve this puzzle and track your Python skills on our interactive Finxter app.</a></p>
<p><strong>Syntax</strong>: You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.reverse()</code></p>
<p><strong>Arguments:</strong> The reverse method doesn’t take any arguments.</p>
<p><strong>Return value:</strong> The method <code>list.reverse()</code> has return value <code>None</code>. It reverses the elements of the list in place (but doesn’t create a new list). Thus, a return value is not needed.</p>
<h2>Python List reverse() Time Complexity</h2>
<p>The <a rel="noreferrer noopener" href="https://wiki.python.org/moin/TimeComplexity" target="_blank">time complexity</a> of the <code>reverse()</code> operation is O(n) for a list with n elements. The standard Python implementation <a href="https://github.com/python/cpython" target="_blank" rel="noreferrer noopener">cPython </a>“touches” all elements in the original list to move them to another position. Thus, the time complexity is linear in the number of list elements. </p>
<p>You can see a plot of the time complexity of the <code>reverse()</code> method for growing list size here:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-25.png" alt="Time complexity of Python List reverse()" class="wp-image-6884" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-25.png 729w, https://blog.finxter.com/wp-content/uplo...00x226.png 300w" sizes="(max-width: 729px) 100vw, 729px" /></figure>
<p><em>The figure shows how the elapsed time of reversing lists with growing number of elements grows linear to the number of elements.</em></p>
<p>If you’re interested in the code I used to generate this plot with <a href="https://blog.finxter.com/matplotlib-line-plot/" target="_blank" rel="noreferrer noopener">Matplotlib</a>, this is it:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import time y = []
for i in [100000 * j for j in range(10,100)]: lst = list(range(i)) t0 = time.time() x = lst.reverse() t1 = time.time() y.append(t1-t0) plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()</pre>
<h2>Python List reverse() In Place</h2>
<p>If you call the <code>list.reverse()</code> method on any list object in Python, it reverses the list elements of <em>this particular list object.</em> You say that the reverse method happens <em>in place</em>. </p>
<p>This is a common mistake of many Python beginners. They assume that the <code>reverse()</code> method creates a new list with the elements in reversed order. This is not the case: the <code>reverse()</code> method modifies only the existing list object.</p>
<p>You can see this in the following example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [1, 2, 3]
>>> lst.reverse()
>>> lst
[3, 2, 1]</pre>
<p>In the example, you only reversed the existing list <code>lst</code>. But you didn’t create a new list!</p>
<h2>Python List reverse() None</h2>
<p>The return value of the <code>list.reverse()</code> method is <code>None</code>. Why? Because the method reverses the list in place. This means that no new list is created. Instead, the method modifies the old list object.</p>
<p>You’ve seen an example of this in the previous section.</p>
<h2>Python List Reverse List Without reverse()</h2>
<p>You can also reverse a list without using the reverse() method. Let’s have a look at the following table that shows all reverse() alternatives:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>lst.reverse()</code></td>
<td>Reverses the order of the elements of list <code>lst</code> <em>in place</em>.</td>
</tr>
<tr>
<td><code>list(reversed(lst))</code></td>
<td>The built-in <code>reversed(lst)</code> method creates a new list object with reversed list elements. </td>
</tr>
<tr>
<td><code>lst[::-1]</code></td>
<td>Slicing with negative indexing is the most concise way of reversing the order of a list. It creates a new list object.</td>
</tr>
<tr>
<td><code>[lst[i] for i in range(len(lst)-1,-1,-1)]</code></td>
<td>Just for fun—one-liner solution to reverse a list using list comprehension and the negative range function.</td>
</tr>
</tbody>
</table>
</figure>
<p>There is a fifth solution using recursion. But it’s highly inefficient and you shouldn’t use it in practice. If you want to learn about it anyways, read on. But don’t tell me you haven’t been warned!</p>
<h2>Python List Reverse Recursive</h2>
<p>You can create a recursive function to reverse any list. I’ll give you the code first and explain it later:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> reverse = lambda lst: reverse(lst[1:]) + [lst[0]] if lst else []</pre>
<p>Let’s check if it does what it’s supposed to do (reversing the list):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> reverse([1, 2, 3])
[3, 2, 1]
>>> reverse(["Ann", 1, 42, 0])
[0, 42, 1, 'Ann']
>>> reverse([])
[]
>>> reverse([1])
[1]</pre>
<p>Okay, it works!</p>
<p>The recursive one-liner solution uses several Python features you have to understand before you can understand it entirely:</p>
<ul>
<li>The lambda function <code>lambda x: y</code> creates an anonymous function with argument <code>x</code> and return value <code>y</code>. <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">You can read the detailed tutorial on the Finxter blog.</a></li>
<li>List concatenation <code>[a, b, c] + [d]</code> creates the new list <code>[a, b, c, d]</code>. <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">You can read the detailed tutorial on the Finxter blog. </a></li>
<li>Slicing <code>lst[startConfusedtop]</code> carves out a subsequence from the list between the <code>start</code> and <code>stop</code> indices. <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">You can read the detailed tutorial on the Finxter blog.</a></li>
<li>The ternary operator <code>x if y else z</code> returns the value <code>x</code> if <code>y</code> is <code>True</code>. In all other cases, it returns the value <code>z</code>. <a rel="noreferrer noopener" href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank">You can read the detailed tutorial on the Finxter blog.</a></li>
</ul>
<p>Phew! Quite some information to digest! But that’s not all. If you’ve understood all of the above, you also need to understand recursion. That’s too much to teach in a single paragraph so I’d send you over to my <a rel="noreferrer noopener" href="https://blog.finxter.com/recursion/" target="_blank">blog article about recursion. </a></p>
<p>I’ll say only that much: to understand recursion, you first need to understand recursion! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Python List Reverse Slice</h2>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Slicing </a>is the easiest way to reverse a list. </p>
<p>To reverse the list <code>lst</code>, you simply use slicing operation <code>lst[::-1]</code> with default <code>start</code> and <code>stop</code> indices (not given) and negative step size <code>-1</code> (given).</p>
<p>There’s only one case where you shouldn’t use slicing to reverse the list and this is if you don’t want to create a new list. In this case, stick to the <code>lst.reverse()</code> method which reverses the list in place.</p>
<p>Here’s an example of slicing to reverse a given list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> friends = ["Ann", "Carsten", "Bob", "Alice"]
>>> r_friends = friends[::-1]
>>> friends
['Ann', 'Carsten', 'Bob', 'Alice']
>>> r_friends
['Alice', 'Bob', 'Carsten', 'Ann']</pre>
<p>You see that the two lists <code>friends</code> and <code>r_friends</code> are independent objects in memory because the slicing operation creates a new list.</p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener">Introduction to Slicing in Python</a></li>
</ul>
<h2>Python List Reverse Copy</h2>
<p>There are two ways to copy a list and reverse the order of its elements: </p>
<ul>
<li>Use slicing <code>list[::-1]</code>, or </li>
<li>Call the<code> reversed(list)</code> method and convert the result to a list using the <code>list(...)</code> constructor.</li>
</ul>
<p>Here are both in action:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst_1 = ['Alice', 'Bob', 'Ann']
>>> lst_2 = lst_1[::-1]
>>> lst_3 = list(reversed(lst_1))
>>> lst_1
['Alice', 'Bob', 'Ann']
>>> lst_2
['Ann', 'Bob', 'Alice']
>>> lst_3
['Ann', 'Bob', 'Alice']</pre>
<h2>Python List Partial Reverse</h2>
<p>To partially reverse a list <code>lst</code>, use slicing with negative step size: <code>lst[startConfusedtop:-1]</code>. The start and stop values define the part of the list to be reversed and the step size -1 means that you go through the list in reversed order. </p>
<p>Here’s an example of some partial list reversals:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> lst[5:2:-1]
['e', 'd']
>>> lst[:1:-1]
['e', 'd', 'c']
>>> lst[3:2:-1]
['d']</pre>
<p>All of those slicing operations reversed a subsequence of the original list. Note that the <code>start</code> index must be larger or equal than the <code>stop</code> index because you traverse the list in negative order (well, if you don’t want to have an empty slice object). </p>
<h2>Python List Reverse List Comprehension</h2>
<p>You can reverse a list with Python’s powerful list comprehension method. (Although I cannot imagine a scenario where this would actually make sense.)</p>
<p><strong>Related article:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">Introduction to List Comprehension</a></li>
</ul>
<p>List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].</p>
<ul>
<li><strong>Expression</strong>: What to do with each list element?</li>
<li><strong>Context</strong>: What list elements to select? It consists of an arbitrary number of for and if statements.</li>
</ul>
<p>For example, the expression <code>[x for x in range(3)]</code> creates the list <code>[0, 1, 2]</code>.</p>
<p>Here’s how you’d use list comprehension to reverse a list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[lst[i] for i in range(len(lst)-1,-1,-1)]</pre>
<p>You go over all indices in negative order—starting with the last list index <code>len(lst)-1</code> and ending in the first list index 0. Note that the stop index is not included in the index sequence so I used the value -1 as the stop index for the <code>range()</code> built-in function. </p>
<h2>Python List reverse() vs reversed()</h2>
<p>What’s the difference between the method <code>list.reverse()</code> and the built-in function <code>reversed(list)</code>?</p>
<ul>
<li><code>list.reverse()</code> modifies an existing list in place and reverses the order of elements in this list object. No new list object is created.</li>
<li><code>reversed(list)</code> creates a new iterable object by reversing the order of elements of the original <code>list</code>.</li>
</ul>
<p>So you should use the former if you don’t want to create a new list and the latter if you want to create a new iterable without modifying the existing list. </p>
<p>An example is the following:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst_1 = [1, 2, 3]
>>> lst_1.reverse()
>>> lst_1
[3, 2, 1]
>>> reversed(lst_1)
&lt;list_reverseiterator object at 0x0000025B58FEC9B0></pre>
<p>The output is not very intuitive but it only means that the <code>reversed()</code> function returns an iterable object.</p>
<h2>Python List Deep Reverse</h2>
<p>What if you want not only to reverse a list but running a deep reverse where all nested lists are also reversed in a recursive manner?</p>
<p>Here’s how you can do it:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
def deep_reverse(lst): ''' Reverses a nested list in place''' # Reverse top-level list lst.reverse() # Recursively reverse all nested lists for element in lst: if isinstance(element, list): deep_reverse(element) lst = [1, 2, 3, [4, 5, 6]]
deep_reverse(lst)
print(lst)</pre>
<p>This generates the output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># OUTPUT: [[6, 5, 4], 3, 2, 1]</pre>
<p>Not only the first-level list is reversed but also the second-level list. The code is loosely inspired from <a href="https://stackoverflow.com/questions/10859135/python-deep-reverse-in-a-list" target="_blank" rel="noreferrer noopener">this article</a>.</p>
<h2>Python List Reverse Enumerate</h2>
<p>The <code>enumerate(list)</code> built-in function returns a list of tuples with the first tuple value being the list index and the second tuple value being the list element. </p>
<p>You can reverse the order of enumerated tuples by stacking together the <code>enumerate()</code> function and the <code>list.reverse()</code> method as follows:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> for i, el in enumerate(list(reversed([1, 2, 3]))): print(i, el) 0 3
1 2
2 1</pre>
<p>This way, you first reverse the list which creates an iterator. You then transform it into a list. The result can be enumerated.</p>
<p>If you want to reverse the order of the indices as well, simply switch the order of both functions:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> for i, el in reversed(list(enumerate([1, 2, 3]))): print(i, el) 2 3
1 2
0 1</pre>
<p>By first enumerating, you calculate the indices based on the original list. Then you reverse them in the outer function.</p>
<h2>Python List Reverse Iterator</h2>
<p>The <code>reversed(list)</code> method returns an iterator, not a new list. This is different: an iterator is more efficient than a list. You can easily convert the iterator object into a list by using the <code>list(...)</code> built-in function.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> reversed([1, 2, 3])
&lt;list_reverseiterator object at 0x0000021735E070B8>
>>> for i in reversed([1, 2, 3]): print(i) 3
2
1</pre>
<p>The iterator object doesn’t look pretty in the shell but it’s a more efficient way to iterate over a sequence of values than using lists. Why? Because lists need to maintain all values in memory. Iterators don’t.</p>
<h2>Python List Reverse Sort</h2>
<p>Do you want to sort a list in descending order? Use the <code>reverse=True</code> argument of the <code>sorted()</code> method. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> sorted([42, 1, 99])
[1, 42, 99]
>>> sorted([42, 1, 99], reverse=True)
[99, 42, 1]</pre>
<h2>Python List reverse() Index</h2>
<p>Rather than just using positive list indices, you can use reverse indexing in Python lists, too. The negative integer index -1 accesses the last element. The negative integer index -2 accesses the second last element and so on. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = ["Alice", "Bob", "Ann"]
>>> lst[-1] 'Ann'
>>> lst[-2] 'Bob'
>>> lst[-3] 'Alice'</pre>
<h2>Python List Reverse range()</h2>
<p>Do you want to iterate over a range of integer values in reverse order? Say, you want to iterate over the numbers from 10 to 0 in reverse order: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0. You can simply achieve this by specifying the <code>start</code>, <code>stop</code>, and <code>step</code> arguments of the <code>range(start, stop, step)</code> method:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> for i in range(10, -1, -1): print(i) 10
9
8
7
6
5
4
3
2
1
0</pre>
<p>Note that the <code>start</code> argument is included in the range but the <code>stop</code> argument isn’t. </p>
<h2>Python List reverse() Doesn’t Work</h2>
<p>What if the <code>reverse()</code> method doesn’t work? Chances are that you assume the <code>list.reverse()</code> method has a return value—that is the reversed list. This is not the case! The <code>list.reverse()</code> method returns <code>None</code> because it reverses the <code>list</code> in place. It doesn’t return a new reversed list.</p>
<p>Here’s an example what you’re probably doing:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [1, 2, 3]
>>> print(lst)
[1, 2, 3]
>>> print(lst.reverse())
None</pre>
<p>If you really want to have a new list with elements in reversed order, use the Python built-in <code>reversed(list)</code> method:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> print(list(reversed([1, 2, 3])))
[3, 2, 1]</pre>
<p>The <code>reversed()</code> method reverses the list and returns the reversed list as an iterator object. You need to convert it to a list first before printing it to the shell (and receiving a meaningful output).</p>
<h2>Python Reverse List NumPy</h2>
<p>To reverse a <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">NumPy array</a> (or even a Python list), you can simply use slicing with negative step size <code>a[::-1]</code>. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> a[::-1]
array([3, 2, 1])</pre>
</p>
<h2>Python List reverse() Thread Safe</h2>
<p>Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as <code>reverse()</code>) are actually <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Thread_safety" target="_blank">thread safe</a>. </p>
<p>In other words: can you call the <code><code>reverse</code>()</code> operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)</p>
<p>The answer is yes (if you use the <a href="https://github.com/python/cpython" target="_blank" rel="noreferrer noopener">cPython </a>implementation). The reason is Python’s <a rel="noreferrer noopener" href="https://wiki.python.org/moin/GlobalInterpreterLock" target="_blank">global interpreter lock</a> that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation. </p>
<p>The only thing you need to know is that each basic operation in the cPython implementation is <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Atomicity_(database_systems)" target="_blank">atomic</a>. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.</p>
<p><strong>All cPython operations are thread-safe. </strong>But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.</p>
<h2>Where to Go From Here?</h2>
<p><strong>The <code>list.reverse()</code> method reverses the order of the list elements. </strong></p>
<p>You’ve learned the ins and outs of this important <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods/" target="_blank">Python list method</a>.</p>
<p>If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: <a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Python One-Liners</a> (Amazon Link). </p>
<p>In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!</p>
<p><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Get the book from Amazon!</a></p>
<p><strong>OFFICIAL BOOK DESCRIPTION:</strong> <em>Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.</em></p>
</div>


https://www.sickgaming.net/blog/2020/03/...t-reverse/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016