avatarDeck451

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4717

Abstract

uilt_in">all</span> <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="c1b4"><pre>Output: <span class="hljs-string">[1, 2, 3, 4, 5]</span></pre></div><h2 id="41f6">list.index()</h2><p id="1d56">This method returns the index of the element passed as an argument. Indexes in Python, as we already know, are nothing more than the positions of elements in the list and their numbering starts at 0.</p><div id="3677"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]</pre></div><div id="d684"><pre><span class="hljs-comment"># get the index of 2</span> <span class="hljs-attr">result</span> = my_list.index(<span class="hljs-number">2</span>)</pre></div><div id="f1da"><pre># <span class="hljs-built_in">print</span> it <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(result)</pre></div><div id="0a18"><pre><span class="hljs-symbol">Output:</span> <span class="hljs-number">1</span></pre></div><p id="9645">Naturally, 2 is found at position 1, so the method returns 1. But extra care is needed when using this method, as we’ll only get an error (exception) if we try to get the index of an element that doesn’t exist in the list:</p><div id="57a2"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]</pre></div><div id="fa28"><pre><span class="hljs-comment"># get the index of 4</span> <span class="hljs-attr">result</span> = my_list.index(<span class="hljs-number">4</span>)</pre></div><div id="23fb"><pre># <span class="hljs-built_in">print</span> it <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(result)</pre></div><div id="6249"><pre><span class="hljs-symbol">Output:</span> Traceback (most recent <span class="hljs-keyword">call</span> last): ... <span class="hljs-symbol">ValueError:</span> <span class="hljs-number">4</span> <span class="hljs-built_in">is</span> <span class="hljs-built_in">not</span> <span class="hljs-keyword">in</span> list</pre></div><h2 id="ee7b">list.insert()</h2><p id="6bcb">This method is very useful when we want to insert an element into a list, but just not at its very end — or else we’d simply use <code>list.append()</code> for that:</p><div id="a60b"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]</pre></div><div id="bf5c"><pre><span class="hljs-comment"># insert the value 4 at position 1</span> <span class="hljs-attribute">my_list</span>.insert(<span class="hljs-number">1</span>, <span class="hljs-number">4</span>)</pre></div><div id="6e93"><pre># <span class="hljs-built_in">print</span> it <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="bc22"><pre>Output: <span class="hljs-string">[1, 4, 2, 3]</span></pre></div><p id="f693">What happened was that Python received the desired index for the desired value and simply altered the list by “making room” for the new element, by shifting some elements (2 and 3) one position to the left, then adding the desired element at the desired position.</p><h2 id="f6d2">list.pop()</h2><p id="5039">What this method does is it simply “pops”, or simply put, removes an element from the list. We can use it with an index argument, so we can tell it what element to remove, or we can use an argumentless <code>list.pop()</code> and it’ll remove the last element from the list.</p><p id="645b">The interesting bit in this method’s behavior is that it also returns the value of the removed element:</p><div id="1e5e"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]</pre></div><div id="2dc7"><pre># <span class="hljs-built_in">remove</span> the <span class="hljs-built_in">last</span> element (<span class="hljs-number">3</span>) my_list.<span class="hljs-built_in">pop</span>()</pre></div><div id="cd72"><pre># <span class="hljs-built_in">print</span> it <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="6538"><pre><span class="hljs-comment"># pop() also returns the removed value.</span> <span class="hljs-comment"># gonna pop the first element (index=0)</span> <span class="hljs

Options

-attr">popped_element</span> = my_list.pop(<span class="hljs-number">0</span>)</pre></div><div id="1f26"><pre><span class="hljs-comment"># print the second popped element</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Just popped: <span class="hljs-subst">{popped_element}</span>"</span>)</pre></div><div id="a0d4"><pre><span class="hljs-comment"># print the list again</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="a121"><pre><span class="hljs-attribute">Output</span>:<span class="hljs-meta"> [1, 2]</span> <span class="hljs-attribute">Just</span> popped: <span class="hljs-number">1</span><span class="hljs-meta"> [2]</span></pre></div><p id="5bf8">Should we provide an index that’s out of our list range, we’ll get an error: <code>IndexError: pop index out of range</code> .</p><h2 id="e155">list.remove()</h2><p id="8dc9">Almost the same as <code>list.pop()</code>, except:</p><ul><li>we must provide the element as argument;</li><li>it does not also return the removed element.</li></ul><div id="8bfd"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]</pre></div><div id="f387"><pre><span class="hljs-comment"># remove 2 from the list</span> my_list.<span class="hljs-built_in">remove</span>(2)</pre></div><div id="3070"><pre># <span class="hljs-built_in">print</span> it <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="271c"><pre>Output: <span class="hljs-string">[1, 3]</span></pre></div><p id="9c4e">As with <code>list.pop()</code>, this one also throws an error if we give it an element outside of the list. If we’d try to <code>my_list_remove(4)</code>, for instance, we’d get this: <code>ValueError: list.remove(x): x not in list</code> .</p><h2 id="dd6f">list.reverse()</h2><p id="91f3">This method does exactly what its name suggests: it reverses a given list:</p><div id="4192"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]</pre></div><div id="8348"><pre># <span class="hljs-keyword">reverse</span> it my_list.<span class="hljs-keyword">reverse</span>()</pre></div><div id="b61e"><pre># <span class="hljs-built_in">print</span> it <span class="hljs-keyword">out</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="4cc3"><pre>Output: <span class="hljs-string">[3, 2, 1]</span></pre></div><h2 id="703c">list.sort()</h2><p id="52fd">This performs an in-place sorting of the original supplied list. We can also provide the named argument <code>reverse=True</code> to sort the list in descending order:</p><div id="2d67"><pre><span class="hljs-comment"># original list</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>]</pre></div><div id="f3a4"><pre># <span class="hljs-keyword">sort</span> the <span class="hljs-keyword">list</span> - ascending <span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span> default my_list.<span class="hljs-keyword">sort</span>()</pre></div><div id="069c"><pre><span class="hljs-comment"># print out the sorted list</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="1783"><pre><span class="hljs-comment"># sort the list - descending order</span> my_list.sort(<span class="hljs-attribute">reverse</span>=<span class="hljs-literal">True</span>)</pre></div><div id="8413"><pre><span class="hljs-comment"># print out the sorted list again</span> <span class="hljs-built_in">print</span>(my_list)</pre></div><div id="2548"><pre>Output: <span class="hljs-string">[1, 2, 3]</span> <span class="hljs-string">[3, 2, 1]</span></pre></div><p id="d0fd">This wraps up the quick review of some of the most frequently used methods available for list objects in Python. Until the <a href="https://readmedium.com/python-up-your-code-tuples-b28c57df7069">next</a> one, keep your mind clear, stay safe and happy coding! Cheers!</p><p id="1c6a"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>. Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a> and <a href="https://www.linkedin.com/company/inplainenglish/"><b>LinkedIn</b></a>. Join our <a href="https://discord.gg/GtDtUAvyhW"><b>community Discord</b></a>.</i></p></article></body>

Up Your Coding Skills with Python: Lists

Part 3: A quick review of some of the most frequently used methods available for ‘list’ objects in Python.

Photo by Ricardo Gomez Angel on Unsplash

Following the previous article, where sensitive and important concepts like shallow and deep copying were discussed in the context of Python lists, this material aims at presenting some of the most frequently used methods that can be used when interacting with list objects.

I admit I am not a big fan of large introductions, so, with your permission, I’d like to get straight to the point of this article — listing and describing the methods we can use on lists.

list.append()

The name is pretty self-explanatory: it allows us to add an element at the end of an existing list object. The syntax is pretty simple and straightforward:

# original list
my_list = [1, 2, 3]
# append one element to the list
my_list.append(4)
# print the list out
print(my_list)
Output:
[1, 2, 3, 4]

list.clear()

As the method name suggests, it successfully empties the list, if it had any elements to begin with:

# original list
my_list = [1, 2, 3]
# remove all elements from the list
my_list.clear()
# print the list out
print(my_list)
Output:
[]

list.count()

This method counts and returns the number of occurrences of the argument’s value in the list:

# original list
my_list = [1, 2, 3]
# count the occurrences of 1 in the list
print(my_list.count(1))
# count the occurrences of 4 in the list
print(my_list.count(4))
Output:
1
0

list.extend()

When you need to append more than one element to your list and you don’t want to use list.append(element) for every element you need to add, or, in other words, when you simply need to “glue” two lists together, list.extend() comes to solve exactly that:

# original list
my_list = [1, 2, 3]
# second list
my_second_list = [4, 5]
# glue them together
my_list.extend(my_second_list)
# print it all out
print(my_list)
Output:
[1, 2, 3, 4, 5]

list.index()

This method returns the index of the element passed as an argument. Indexes in Python, as we already know, are nothing more than the positions of elements in the list and their numbering starts at 0.

# original list
my_list = [1, 2, 3]
# get the index of 2
result = my_list.index(2)
# print it out
print(result)
Output:
1

Naturally, 2 is found at position 1, so the method returns 1. But extra care is needed when using this method, as we’ll only get an error (exception) if we try to get the index of an element that doesn’t exist in the list:

# original list
my_list = [1, 2, 3]
# get the index of 4
result = my_list.index(4)
# print it out
print(result)
Output:
Traceback (most recent call last):
...
ValueError: 4 is not in list

list.insert()

This method is very useful when we want to insert an element into a list, but just not at its very end — or else we’d simply use list.append() for that:

# original list
my_list = [1, 2, 3]
# insert the value 4 at position 1
my_list.insert(1, 4)
# print it out
print(my_list)
Output:
[1, 4, 2, 3]

What happened was that Python received the desired index for the desired value and simply altered the list by “making room” for the new element, by shifting some elements (2 and 3) one position to the left, then adding the desired element at the desired position.

list.pop()

What this method does is it simply “pops”, or simply put, removes an element from the list. We can use it with an index argument, so we can tell it what element to remove, or we can use an argumentless list.pop() and it’ll remove the last element from the list.

The interesting bit in this method’s behavior is that it also returns the value of the removed element:

# original list
my_list = [1, 2, 3]
# remove the last element (3)
my_list.pop()
# print it out
print(my_list)
# pop() also returns the removed value.
# gonna pop the first element (index=0)
popped_element = my_list.pop(0)
# print the second popped element
print(f"Just popped: {popped_element}")
# print the list again
print(my_list)
Output:
[1, 2]
Just popped: 1
[2]

Should we provide an index that’s out of our list range, we’ll get an error: IndexError: pop index out of range .

list.remove()

Almost the same as list.pop(), except:

  • we must provide the element as argument;
  • it does not also return the removed element.
# original list
my_list = [1, 2, 3]
# remove 2 from the list
my_list.remove(2)
# print it out
print(my_list)
Output:
[1, 3]

As with list.pop(), this one also throws an error if we give it an element outside of the list. If we’d try to my_list_remove(4), for instance, we’d get this: ValueError: list.remove(x): x not in list .

list.reverse()

This method does exactly what its name suggests: it reverses a given list:

# original list
my_list = [1, 2, 3]
# reverse it
my_list.reverse()
# print it out
print(my_list)
Output:
[3, 2, 1]

list.sort()

This performs an in-place sorting of the original supplied list. We can also provide the named argument reverse=True to sort the list in descending order:

# original list
my_list = [2, 1, 3]
# sort the list - ascending order by default
my_list.sort()
# print out the sorted list
print(my_list)
# sort the list - descending order
my_list.sort(reverse=True)
# print out the sorted list again
print(my_list)
Output:
[1, 2, 3]
[3, 2, 1]

This wraps up the quick review of some of the most frequently used methods available for list objects in Python. Until the next one, keep your mind clear, stay safe and happy coding! Cheers!

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

Python
Programming
Coding
Tutorial
Lists
Recommended from ReadMedium