avatarMurtaza Ali

Summarize

A Few Must-Know Python List Functions You’ll Thank Yourself for Learning

This little Python data structure is more powerful than you might think.

Photo by Kevin Canlas on Unsplash

Lists are one of the most commonly used data structures in Python, an enhanced version of arrays that support a host of different operations. That said, most programmers are unaware of just how many functions accomplish fascinating things with lists. In this article, I take an example-based approach to show you every Python list function you’ll ever need.

Let’s get into it.

Starting out Simple

More often than not, the length of a list is a helpful statistic to have. Compute it easily with the len function:

>>> my_fruits = ['apple', 'banana', 'kiwi']
>>> len(my_fruits)
3

Hmm, but what if you’re also in the mood for some mango? How can you add that to my list? The append function will come in handy here:

>>> my_fruits.append('mango')
>>> my_fruits
['apple', 'banana', 'kiwi', 'mango']

Importantly, the append function does not return anything; it just adds the specified element to the end of your list. Appending one by one seems tedious, though. You might wonder, if you have a bunch of fruits in a separate list, can you just append them all at once? You can, but it might not give you the result you’re looking for:

>>> more_fruits = ['papaya', 'boysenberry', 'watermelon']
>>> my_fruits.append(more_fruits)
>>> my_fruits
['apple', 'banana', 'kiwi', 'mango', ['papaya', 'boysenberry', 'watermelon']]

Because append is designed to add a singular item to the end of a list, this just results in sticking the entire second list into the first one. What you’re looking for is the extend function, which takes the items from the second list and adds them one by one to the first list:

>>> my_fruits = ['apple', 'banana', 'kiwi']
>>> more_fruits = ['papaya', 'boysenberry', 'watermelon']
>>> my_fruits.extend(more_fruits)
>>> my_fruits
['apple', 'banana', 'kiwi', 'papaya', 'boysenberry', 'watermelon']

Voila!

Getting a Little Funkier

Okay, so now, what if you want to eat a blueberry to ensure you get your fair share of antioxidants? Additionally, you want it to be at the beginning of your list. This can be accomplished via the insert function, which takes in an index as its first argument, and the element to insert as its second argument:

>>> my_fruits.insert(0, 'blueberry')
>>> my_fruits
['blueberry', 'apple', 'banana', 'kiwi', 'papaya', 'boysenberry', 'watermelon']

Additionally, you have finished eating your apple, and so you need to remove it from your list. The pop function comes in handy here. It takes as input the index of the element to be removed.

>>> my_fruits.pop(1)
'apple'
>>> my_fruits
['blueberry', 'banana', 'kiwi', 'papaya', 'boysenberry', 'watermelon']

It’s a tad different from the previous functions in that it also returns the element removed, which can be useful.

Next, you want to extend your list with 50 grapes, but it feels like an immense waste of time to type out “grape” 50 individual times. Luckily, it’s actually possible to multiply a list and a number to accomplish this task!

>>> grapes = ['grape']
>>> grapes = grapes * 50
>>> grapes
['grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape', 'grape']

After extending your fruits list by it, you can use the count function to ensure that all the grapes were successfully added:

>>> my_fruits.extend(grapes)
>>> my_fruits.count('grape')
50

Topping it All Off

You’ve collected a lot of fruits thus far, but you realize that you might not be getting enough nutrients. As a result of this, you decide to include both a fruit and a vegetable in all your meals. These start out as two separate lists:

>>> fruits = ['mango', 'watermelon', 'orange']
>>> vegetables = ['zucchini', 'potato', 'serrano pepper']

You want to combine these lists together in such a way that the matching indices from each list are paired together as tuples. This is a task very easily accomplished with the zip function. This returns a zip object, so we need to convert it back into a list:

>>> zip(fruits, vegetables)
<zip object at 0x000002BDD2281040>
>>> list(zip(fruits, vegetables))
[('mango', 'zucchini'), ('watermelon', 'potato'), ('orange', 'serrano pepper')]

What’s cool about the zip function is that you can also reverse the list back into its component parts. You just need to specify this using the * operator:

>>> fruits, vegetables = zip(*temp)
>>> fruits
('mango', 'watermelon', 'orange')
>>> vegetables
('zucchini', 'potato', 'serrano pepper')

* separates the tuples, so you can read the above as zip(('mango', 'zucchini'), ('watermelon', 'potato'), ('orange', 'serrano pepper')) . zip then does the exact same thing as before, matching the indices of each respective tuple to give us back our collective fruits and vegetables.

Final Thoughts

The above functions have been extremely helpful for me, and I hope they can be for you as well. As someone who programs in Python regularly, being familiar with these list capabilities is an invaluable skill. With that, I’ll leave you until next time.

Happy listing, folks!

Want to excel at Python? Get exclusive, free access to my simple and easy-to-read guides here.

Please consider using my referral link below to sign up as a full-fledged Medium member. You will be able to read unlimited stories a month, and your membership fee directly supports me and other writers.

References

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

Data Science
Programming
Education
Technology
Python
Recommended from ReadMedium