Sunday, December 24, 2017

Python Lists

As a data scientist, you'll often want to work with many data points. 
If you for example want to measure the height of everybody in your family, and store this information in python, it would be inconvenient to create a new python variable for each data point you collected right?
What you can do instead, is store all this information in a python _list_. 
You can build such a list with square brackets. Suppose you asked your two sisters and parents for their height, in meters. You can build the list as follows:
Of course, also this data structure can be referenced to with a variable. Simply put the variable name and the equals sign in front, like here:
A list is a way to give a single name to a collection of values. These values, or elements, can have any type; they can be floats, integer, booleans, strings, but also more advanced Python types, even lists.

Lists can also contain lists themselves. Instead of putting the strings in between the numbers, you can create little sublists for each member of the family. One for liz, one for emma and so on.
 Now, you can tell Python that these sublists are the elements of another list, that I named fam2: the little lists are wrapped in square brackets and separated with commas. 
We're dealing with a new Python type here. These calls show that both `fam` and `fam2` are lists. 
Subsetting Lists
You can also count backwards, using negative indexes. This is useful if you want to get some elements at the end of your list. To get your dad's height, for example, you'll need the index -1. These are the negative indexes for all list elements.
Apart from indexing, there's also something called slicing, which allows you to select multiple elements from a list, thus creating a new list. You can do this by specifying a range, using a colon.

Can you guess what it'll return?
Apparently, only the elements with index 3 and 4, get returned. The element with index 5 is not included. In general, this is the syntax: the index you specify before the colon, so where the slice starts, is included, while the index you specify after the colon, where the slice ends, is not.
You can also choose to just leave out the index before or after the colon. If you leave out the index where the slice should begin, you're telling Python to start the slice from index 0, like this example.
If you leave out the index where the slice should end, you include all elements up to and including the last element in the list, like here:


Post a Comment


Talk to us (+91-9738925800)