top of page

Python lists

  • Writer: Perry
    Perry
  • Nov 2, 2018
  • 4 min read

A list in Python is a Data Structure, which is an ordered group of elements, created by placing all elements (items) between square brackets [ ], separated by commas.


ree

Elements of a list in Python may be of different types (int, str, float, etc) and unlike other languages (e.g. R), coercion will not occur. A list in Python can also have another list as an element, this is called a nested list. Unlike strings, which I will cover soon, lists are mutable.

A mutable object is an object whose state can be changed after it is created. Objects of common types of list, set and dict are mutable and objects of common types of int, str, float, bool and tuple are immutable.

To get started, let's create a nested list as follows:

Indexing lists

Since a list is an ordered sequence of items, we can use indexing (using the index operator ([ ]) to access its elements. There are a few ways to do this:

ree
  • Direct indexing ( + )

Index starts from 0, which corresponds to the first or the left-most element of a list. A list of size N has index from 0 to N-1.

  • Reverse indexing ( - )

Python also allows for negative indexing: -1 refers to the index of the last item.

  • Slicing ( : )

Slicing (using a colon) is another way of accessing elements of a list. [i : j] selects all elements with an index between i (inclusive) and j (exclusive). If i or j is empty, that indicates the first or the last element, respectively.

Note that the output itself is a list.

Question: what will my_list[:] output? Leave a comment at the end of this post! 👩🏻‍💼


Modifying lists

Since lists are mutable, we can change them using an equal sign ( = ).

We can also combine the slicing operator and equal sign to modify multiple items in a list:

Remember: the index to the right of the colon is exclusive, therefore in the example above, only items with index 1 and 2 were modified.


Question: What is the output of the following? Leave a comment at the end of this post! 👩🏻‍💼

Now that you are familiar with the fundamentals of Python lists, let's talk about lists methods, which are just like functions, defined particularly for list objects to make working with lists easier and more efficient.

Note: Lists methods will all modify the original list, this is because a list is a mutable object, so any changes you make using list methods impact the original list.


Lists Methods



We can add a single item to a list using append() method. Note that this single item may also be a list itself.



To add multiple items to a list, we use extend() method.

The interesting difference between append() and index() is when a list is added. append() treats the list as a single item, whereas extend() treats each item of that list as an individual item, see the example below:

Versus:

We have not yet talked about strings in Python, but it is worth noting here that a string consists of several characters and is treated like a list:

That's probably not what you were expecting! Pay attention to append and extend differences.



While with extend() or append() methods you can only add to the END of a list, insert() method gives you the option to add an element at any location. Similar to append (and despite extend()), if you insert a list, the list would be added as one single item, hence you will have a nested list.

To add to the end of a list with insert(), we entered the index of the last free space, the index of such element is equal to the length of the list, which you can get using the function len().

Note: You could also use += or *= to add to a list. See more on that here.



remove() method removes the FIRST occurrence of an item from a list. ☝🏻

If you want all occurrences of an item to be removed you may take a functional approach by writing a simple function or you may call remove for multiple times:

while 'is' in my_list: my_list.remove('is')



pop() method removes and returns the last element if index is not provided!

Usually if you want to keep track of the element that you are about to remove, you use a variable to store the output of pop().



clear() method removes all elements from a list, your list would be an empty list then.

del function is used to delete objects, so if you do del my_list it would delete the entire list. If you'd like to delete some elements of the list not all, there are various ways: one would be to use del but on a selected elements, for example: del my_list[2:5]

Note: same as methods, del function also modifies the original list.



index() method returns the index 🔢 of the FIRST matched element to the item passed as an argument. If the value does not exist in the list, we'll get "ValueError: 4 is not in list"



count() method returns the number of elements in the list that match the item passed as an argument. If the item does not exist in the list, count() would return 0.



reverse() method would reverse the order of the elements in a list. After reverse() is applied new_list[0] = old_list[-1] and new_list[-1] = old_list[0]



sort() rearranges the elements of a list in an ascending (increasing) order. An important point here is that, although the elements of a list in Python could be of any type, for sort() function to work you need to have same-type elements. This is because the sort function performs pair-wise comparison between elements and of course you can only compare 🍎 to 🍎, i.e. an str() cannot be compared with an int() or a list(). See my previous post here for further clarification on this.


Good Luck Data Scientists to Be!

1 Comment


Alankar Mahajan
Alankar Mahajan
Nov 11, 2018

In the list methods section you are talking about append() and extend() but in this line you wrote index:


The interesting difference between append() and index() is when a list is added. append() treats the list as a single item, whereas extend() treats each item of that list as an individual item, see the example below

Like

© 2023 by Salt & Pepper. Proudly created with Wix.com

SUBSCRIBE VIA EMAIL

me_edited.jpg
bottom of page