Python List Comprehension
Learn how to effectively use list comprehension in Python to create lists, to replace (nested) for loops and the map(), filter() and reduce() functions, ...!
When doing data science, you might find yourself wanting to read lists of lists, filtering column names, removing vowels from a list, or flattening a matrix. You can easily use a lambda function or a for a loop; As you well know, there are multiple ways to go about this. One other way to do this is by using list comprehensions.
This tutorial will go over the following topics in list comprehension:
- You'll first get a short recap of what Python lists (Invalid URL) are and how they compare to other Python data structures;
- Next, you'll dive into Python lists comprehensions (Invalid URL): you'll learn more about the mathematics behind Python lists, how you can construct list comprehensions, how you can rewrite them as for loops or lambda functions.
- When you've got the basics down, it's also time to fine-tune your list comprehensions by adding conditional (Invalid URL) statements to them: you'll learn how you can include conditions in list comprehensions and how you can handle multiple if conditions and if-else statements.
- Lastly, you'll dive into nested list comprehensions (Invalid URL) to iterate multiple times over lists.
If you're also interested in tackling list comprehensions together with iterators and generators? Check out DataCamp's Python Data Science Toolbox course!
By now, you will have probably played around with values that had several data types. You have saved each value in a separate variable: each variable represents a single value. However, in data science, you'll often work with many data points, which will make it hard to keep on storing every value in a separate variable. Instead, you store all of these values in a Python list.
(Invalid URL)
Python Lists
Lists are one of the four built-in data structures in Python. Other data structures that you might know are tuples, dictionaries, and sets. A list in Python is different from, for example, int or bool, in the sense that it's a compound data type: you can group values in lists. These values don't need to be of the same type: they can be a combination of boolean, String, integer, float values.
List literals are a collection of data surrounded by brackets, and the elements are separated by a comma. The list is capable of holding various data types inside it, unlike arrays.
For example, let's say you want to build a list of courses then you could have:
courses = ['statistics', 'python', 'linear algebra']
Note that lists are ordered collections of items or objects. This makes lists in Python "sequence types", as they behave like a sequence. This means that they can be iterated using for loops. Other examples of sequences are Strings, tuples, or sets.
Lists are similar in spirit to strings you can use the len() function and square brackets [ ] to access the data, with the first element indexed at 0.
Tip: if you'd like to know more, test, or practice your knowledge of Python lists, you can do so by going through the most common questions on Python lists here.
Now, on a practical note: you build up a list with two square brackets (start bracket and end bracket). Inside these brackets, you'll use commas to separate your values. You can then assign your list to a variable. The values that you put in a Python list can be of any data type, even lists!
Take a look at the following example of a list:
# Assign integer values to `a` and `b`
a = 4
b = 9
# Create a list with the variables `a` and `b`
count_list = [1,2,3,a,5,6,7,8,b,10]count_listNote that the values of a and b have been updated in the list count_list.
Creation of List
A list is created by placing all the items inside a square bracket [] separated by commas. It can have an infinite number of elements having various data types like string, integer, float, etc.
list1 = [1,2,3,4,5,6] # with same data type
list1list2 = [1, 'Aditya', 2.5] # with mixed data type
list2Accessing Elements from a List
Elements from the list can be accessed in various ways:
-
Index based: You can use the index operator to access the element from a list. In python, the indexing starts from 0 and ends at
n-1, where n is the number of elements in the list.Indexing can be further categorized into positive and negative indexing.
index = [1,2,3,4,5]
index[0], index[4] # positive indexing