Learn Python 2: lists and for loops pt 1


Storing multiple items in a list is a convenient way for easy indexing. Let's assume we have a ball with four variables: x position, y position, x velocity, and y velocity. We can create a list to store these variables.

ball = [0] * 4

Initially, the list will have four values, all equal to 0. But what if we wish to set the x position to 5 and the y position to 9?

ball[:2] = [5,9]

To do this, we can replace the first two values in the list with 5 and 9, respectively. We can achieve this by slicing the list using the colon operator. In this case, we take all the values up to index 2, which refers to indexes 0 and 1 in the list.

Now let's look at a program that takes a list of values and squares each value.

values = [1,2,3,4,5,6,7,8,9]
for i in range(len(values)):
    values[i] *= values[i]
print(values)

his code uses a "for" loop to iterate through a list of 9 values, numbers 1 through 9. Firstly, we declare the list. Then, we declare a for loop with the len() method, which returns the length of the list as an integer, 9 in our case. The range() function tells the interpreter to iterate n number of times, which is also 9 in our case. The next line, which is inside the for loop, uses the "i" variable to store the current value of the loop, ranging from 0 to 8. We use this variable to access each value of the list multiply it by itself using the *= operator, and then store the result in its place. This indentation indicates that the line is inside the for loop. Finally, the last line prints the updated list.


Lists and loops are some of the more useful features in beginner Python development. We will expand more on this in another post, but until then, stay tuned for if statements and flow control in my next post. and as always, Keep exploring and happy coding!

 

How do you rate this article?

5


gittygiddy
gittygiddy

i love cats


Learning Python: A to Z blog
Learning Python: A to Z blog

Python is a powerful programming language used in web development, data science, machine learning, and artificial intelligence. Our community offers comprehensive learning, with experienced developers guiding learners. Join us to collaborate on exciting projects and unlock your full potential as a programmer.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.