Lists are by far the most common data type you will use in Python. I wanted to take a few minutes to see how easy Python make the use os lists. I also want you to notice how much ground we can cover by just thinking about these properties of a list. In this article we will talk about lists, functions, searching, return values, data tpes, diconaaries, try-catch try-except blocks and more interesting Python techniques.
So we will be finding the average, min, max and mode of a list. I won’t go into different theories on how to efficiently find these, but rather straight forward approach. Let us start by an assumption that all the values in our list are going to be integers and the data is already stored in a variable named list. As before, we will be using Python 2.7, here is a copy of if you need it. Coming from that we can start by saying our main function looks like this:
def main: list = [3, 4, 1, 20, 102, 3, 5, 67, 39, 28, 10, 1, 4, 34, 1, 6, 107, 99] avg(list) min(list) max(list) mode(list)
This will simply call 4 different functions that will each find and print what we are looking for. First, lets go over some list basic properites. In all these function we will use for loops to iterate over the elements of the array. Lucky Python has a simple syntax that allows us to have a variable in the for loop that will take the values of the array.
What does this mean? You will recall that arrays have 0 indexing property that allows us to access the elements in the array directly. If we were to have the syntax list is our example, the value will correspond to 3. the syntax list will have the value 4. We can access each element individually and directly. We can use this to change values in the array. If we were to have list = 55 in our code, the value of list will change to be 55. Here is an example code:
list = [3, 4, 1, 20, 102, 3, 5, 67, 39, 28, 10, 1, 4, 34, 1, 6, 107, 99] print list print list print list list = 55 print list print list
This code will output:
Notice that the values of the list have changed after the assignment. Now let us recall the for loop syntax and properties in Python. The syntax is for element in sequence. That means that we need to provide a name of a variable, in this case element and a sequence such as a String, List, Tuple, etc. So if we wanted to print the numbers 1 to 10 in Python, we will need a list sequence with the numbers in a list and then we can just print element. Like this:
You might also like
Photo Jigsaw Puzzle of Carpet PYTHON
Home (Ardea Wildlife Pets)