Lists and Functions in Python
In addition to DataFrames, there are two foundational Python principles important to Data Sciences: A Python list and Python functions.
Creating Lists in Python
A list is a built-in data structure in Python, meaning we do not need to import any libraries to use it, and is used to store a collection of items (in order).
- You can use any Python variable name for a list, though it's common for a list's variable name to be descriptive of the contents of the list.
- To create a new list, you use a set of square brackets. For example,
emptyList = []creates a Python variable namedemptyListthat contains a list with zero elements. - To include elements within a list, separate each element by a comma and include them in the list. For example,
numbers = [42, 107, 300]creates a Python variable namednumbersthat contains a list of three numbers. You can also use strings (ex:cities = ["Chicago", "New York"]) or mixed types (ex:values = ["CS", 107]).
Try out creating simple lists:
[107, 207, 307]
Appending Elements to a List
Python provides the ability to add to the end of the list through the append function on the list. Using the variable name of the list, like myList, the syntax myList.append(407) adds the value 407 to the list.
Try appending to a list in Python:
["apple", "blueberry"]
Reading a Specific Element from the List
When you refer to the list by it's variable name, you refer to the entire list. Python also provides access to individual elements of the list by accessing elements by the index location.
- An index location is the zero-based location of the element in the list. This means that the first element of the list is index
[0], the second element is index[1], and so on. - To access the element, use the list's name following by the index syntax. For example, using a list stored in the variable named
myList, we can access the first element in the list by the syntaxmyList[0].
Try out accessing elements in a Python list:
('Illinois', 'Wisconsin')Creating Functions in Python
In addition to lists, Python provides functions to to group blocks of code that perform a specific task. The use of functions will help make our code more organized, readable, and efficient by avoiding repetition and allowing the same code to be used in multiple places. Functions will:
- take inputs (called parameters),
- perform operations, and
- return an output value.
Python provides many built-in functions, and you can also define your own using the def keyword. To start, we can begin with an example function and returns the result of adding 10 to the input parameter:
35