. Advertisement .
..3..
. Advertisement .
..4..
Computers are mostly used to store information and extract information from it. Python is one of the most powerful programming languages. We can use Python to get computers to do most routine processes. This blog is all about ”For loop increment by 2 in Python”.
How can you loop increment by 2 in Python?
Approach 1: Utilize the slicing method
You can utilize the slicing method for loop increment by 2 in Python. The list values are increased by two steps using the slice operator :
in this manner. The starting index in the code is represented by the first digit, which defaults to 0, the ending slice index is represented by the second digit, which defaults to the end of the list, and the step is represented by the third digit.
Let’s look at an example of this:
mylist = [1,2,3,4,5,6,7,8]
for x in mylist[1::2]:
print (x)
Result:
2
4
6
8
Note that this approach replicates the original list to a new memory location, so be careful with it. If the list is enormous, the speed performance will be poor.
Approach 2: Utilize range()
Another way to for loop increment by 2 in Python is using range(). Start
, Stop
, and Step
are its three available parameters. With the exception of the stop
value, this function iterates the value from start
value and increasing by the specified step
.
for x in range(1, 13, 2):
print(x)
Result:
1
3
5
7
9
11
Conclusion
For Loop Increment by 2 in Python is a confusing problem. We hope this blog provides useful information for you. If you have more questions about this topic, please comment below. Thank you for reading, we are always excited when one of our posts can provide useful information on a topic like this!
Read more
Leave a comment