Python Lists Cheat sheet | Towards Data Science

List — The built-in, array-like data structure in Python!
List is one of the most frequently used data structure in Python and it is mutable or changeable, ordered sequence of elements of same or different data types.
Here are the 5 must-know tweaks and tricks about Python list, which I mastered (and certainly you can) in just 5 minutes. ⏳
Using these methods, I can write my code seamlessly and so, sharing this interesting piece with everyone.
Lists are defined by having values between square brackets [ ]. Each element which is inside [ ] is called an item.
mylist = ['TDS', 'medium', 597, 99.99, True, 'Learn']
💡 You can copy all the list methods from this Gist and follow along! The answers are already mentioned just below it.
With interesting example, Let’s get started!
Index is the position of an item in the iterable. As List is an iterable, an item in the list is accessible by putting its index in the [ ].
As Python is a 0 indexed language i.e. indexing starts from 0.
for example, first element of the below list can be retrieved by using its index as 0.
mylist = ['TDS', 'medium', 597, 99.99, True, 'Learn']mylist[0] # output --> 'TDS'
However, often times, we are interested in getting 2nd last or the last element of the list. In such cases, we can use Reverse Indexing.
In reverse indexing, the indexing starts from -1 at the end of the list. Below picture clarifies the concept.
Here is an example which generates same results by using indexing and reverse indexing.
Next,Slicing ✂️ is the method of creating a new list by selecting or extracting few items from the existing list. There are a few syntaxes for accessing a range of items from the existing list. The below picture is self-explanatory for it.
If negative integers are used for slicing, it will be the case of reverse indexing.
Commonly, we need to add the a element or list of elements to the existing list.
.append(), .extend() and .insert() are the solutions
Python list method .append() adds its argument as a single element to the end of a list.
Every time, length of mylist is increased by 1.
In the last line of above example, another list [‘D’, ‘B’] is added as a single item with its original data type list at the end of mylist.
But, if you want to add each element of the list [‘D’, ‘B’] at the end of mylist, then list.extend() is your best friend.
Python list method .extend() iterates over its arguments (if argument is iterable) and adds each element to the list. In this case, the length of the list increases by number of elements in it’s argument.
list.extend() looks more safe than list.append() when you want to add add an element to the list.
🚩 Then why NOT to use list.extend() everywhere??
As .extend() is based on iterative approach, it is significantly slower than .append()
Well, these both methods add a new element at the end of existing list.
You can add an item at a desired position in existing list, using the method .insert(). 💡
After adding an item to the list, now let’s explore the methods to remove an item from list.
As easy as adding an item, removing an item from list is even easier.
.remove(), .pop() and .clear() are at your help!
The list method .remove() will remove a specific item from the list. By default, it will remove only the first occurrence of the item. A ValueError will be raised if specified item is not in the list.
Sometimes, we need to extract an item from a specific index and use it for the further processing. List method .pop() is absolutely useful in such case.
.pop(index) results out the item at mentioned index from the list. A IndexError will be raised if the list is empty or an index is out of range.
As seen in the above picture, if no index is mentioned, .pop() returns the last item by default.
The list method .clear() removes all the items from the list and returns an empty list.
mylist = ['TDS', 'medium', 597, 99.99, True, 'TDS', 100] mylist.clear() mylist#Output: []
However, using the keyword del, the list can be permanently deleted.
In my automation projects, every time I needed to check the presence of a specific item in the list.
And I found, using in and not in is more Pythonic!
Here is how!
It is an elegant way of creating Lists in Python. The most popular usage of list comprehensions is to create lists concisely. Its basic syntax is,
[expression for item in iterable]
for example, a string “DataScience” is an iterable. So we can form a list of letters of this string.
Here is an interesting read about detailed know-how of list comprehension!!
towardsdatascience.com
Other list methods such as .copy() , .sort() and .reverse() can be found in below gist and in this Must-Read.
A step further, here is a simple gist with all the list methods at one place.
🚩 Looking for answers?? ➡️ You can check your answers in this Notebook!
Summing up,
I found these List methods quite handy while using Python for Data Analysis as well as complex automation tasks. Some of them such as append , in and not in are most frequently used, while others such as list comprehension, pop are extremely useful and efficient in some situations.
Now you can read unlimited stories by me and thousands of other writers by becoming a Medium member — just sign up here. when you do so, I will get a small portion of your fees without any additional cost. Feel free to join my email list to stay updated about my writing.
Thank you for reading and investing your time!!