List comprehensions are a powerful tool for building lists. A list comprehension is similar to a generator expression, except that instead of returning a single value, the list comprehension returns a whole list.
The first way we learn about list comprehensions is in our introduction to programming course.
What happens here? We create a list comprehension that says “for each number in, get the squared value of that number”. As we know, if we wanted to do this without using a list comprehension, we could use nested loops. A general statement for doing this would be:
for x in range(0,n+1):
y= n * x
Let's take a closer look at how Python handles these types of things. For simple cases, a list comprehension can often be simplified into a regular function call, or even just a simpler loop. Let's say we want to find out what the sum of numbers from 0–9 is. Here's the equivalent code:
But, let's say we want to know the sum of positive numbers only. In this case, we need to filter the values before adding them together. We might think we could add a condition to check if each item was positive, then return the total, but that doesn't work! Instead we'll have to use a list comprehension to build the sum. Using the same formula from above, we'd write:
Here, we're starting off with a list comprehension that says, "take the first item in the range object". Then, we're saying, "for each item following that, multiply it by the previous item." If we were to try this code, we'd see an error message telling us that the index out of range error was thrown. To fix this issue, we simply replace with. This means, "start off with a list containing just the range object," then iterate over each item inside of the range object. This gives us a working solution:
Generator expressions are a way to create lists without using a loop. You use them when you want to iterate over something and return each item in turn.
Dictionaries are data structures that map keys to values. In Python, they are implemented as associative arrays.
Tuples are immutable sequences of objects. They are created by separating items with commas.
Sets are unordered collections of unique elements. They are created by putting elements into a collection.
Strings are sequences of characters. They are created by joining together strings with the + operator.
Functions are self-contained units of code that perform some task. They are created by defining a function definition inside parentheses.
1. What do we call these?
A sequence is a list of numbers that starts at one then goes to some number and repeats. In Python, they are called lists. There are many ways to create lists in python. You can start with an empty list via (the square brackets) or just type in some comma separated values. We'll use both methods throughout our code examples.
2. How to create a list.
These items were listed under the header “shopping cart”, which was created using a list comprehension. A list comprehension is a way to create a list from an expression. Here's how:
Here, we're adding several things to the front of our list, and then appending them to the back. So here's what that looks like:
Next I'm going to take the second item in the list and put it in quotes. Here's where all of our items get concatenated together.
Python sequences help us find patterns in data-sets. We can use them to look for trends and patterns in numbers and data we collect. To start off, let's begin by looking at each number individually, and then how to identify if they have any pattern.
for i in range (len(data)):
if any(x y for x,y in zip(data,data)):
print("There is some sort of pattern")
As you can see, we first list our set of data inside brackets, and then loop over the length of our sequence. Once we've done this, we can now add in a conditional statement to check if anything matches. In this case, we're checking if any of the values match a value within 10 units away.
If any do, we would print out the word "there", otherwise, we would print out "no pattern." You'll notice that I'm using the format command, which does exactly what its name implies. Its arguments are the string value you want to output on screen, followed by a placeholder for where the value should go. So, my code above outputs "54" then "73", then "87", and so forth.
A sequence contains elements, each of which is an object of some type. You assign values to its attributes via dot notation. You access individual elements using square brackets.
for num in nums:
This prints 1 2 3 out. Each time you loop over a list, you get a new copy of the exact same thing. Elements cannot change the values of other elements, only themselves. If you want elements to change, you need to make copies first.