So far we’ve just touched on the two fundamentals aspects of programming. We’ve seen how to define variables and how to define and call functions in Python. Given what we’ve covered, we can now write the following.

def f(x):
	return x**2
	
print(f(0))
print(f(1))
print(f(2))
print(f(3))
print(f(4))

Looking at this code, it’s clear that it’s repetitive. It is applying the same pair of functions to a group of consecutive numbers. We can express it in a more compact manner by making use of lists and Loops in Python.

Lists

A list is an order set of elements (can be a mix of str/int/float/bool/etc) denoted by [] where elements are separated by a comma. For example, we could create a list of things on my desk as follows:

things_on_my_desk = ['Monitor', 'laptop', 'coffee mug', 'Sanpellegrino', 'books']

Lists are central to data analysis, so it will be helpful to get comfortable adding elements to list, referencing elements in a list, etc. We can add an element to a list by using the append function. Notice that when we add an element to a list in Python, we don’t use the assignment operator =

things_on_my_desk.append('microphone')

We can select elements from a list by writing the list’s name followed by brackets containing the position of the element in the list that we would like to select. Python does zero based indexing though which means to select the first element we would write things_on_my_desk[0]and select the third, we would write things_on_my_desk[2] . Also include an example of range

For Loops

We now understand that we can begin re-writing the initial code block by creating a list: my_list = [0, 1, 2, 3, 4] . The part that remains to understand is how to apply the same function to each element of the list. For loops, as well show, is one way to do so in Python.