SoFunction
Updated on 2024-10-29

Python for loop iterates through sequence indexing process explained

This article introduces the Python for loop through the sequence of index iteration process analysis, the text of the sample code through the introduction of the very detailed, for everyone's learning or work has a certain reference value of learning, the need for friends can refer to the following

Python for loops iterate through sequence indexes:

Note: Collections and dictionaries cannot be indexed because they are unordered.

Use the len (argument) method to get the length of the traversed object.

Program:

strs = "Hello World."
# Use the len method to get the length of the traversed object.
print(len(strs))
# 12
lst = [7,8,9,4,5,6]
print(len(lst))
# 6
tup = (1,2,3,7,8,9)
print(len(tup))
# 6

Use the range method (left-closed, right-open):

The range function has the following parameters, start position, end position (not included), step size.

Note: The start position defaults to 0.

The step size can be negative, the default is 1.

Program:

# range function (start position, end position, step size)
# Note: The starting position defaults to 0.
# The step size can be negative, the default is 1.
lst = [i for i in range(5)]
print(lst) # Start position defaults to 0
# [0, 1, 2, 3, 4]

lst = [i for i in range(1,5)]
print(lst) # Does not contain a termination position
# [1, 2, 3, 4]

lst = [i for i in range(1,5,2)]
print(lst) #Steps can be changed to suit your needs
# [1, 3]

lst = [i for i in range(-5,-1,1)]
print(lst) # Start and end positions can be negative
# [-5, -4, -3, -2]

lst = [i for i in range(8,5,-1)]
print(lst) # The step size can be negative
# [8, 7, 6]

Iterative operation program by sequence indexing:

String:

strs = "Hello World."
for i in range(len(strs)):
  print(strs[i],end = " ")
#   H e l l o  W o r l d .

List:

lst = [7,8,9,4,5,6]
for i in range(len(lst)):
  print(lst[i],end = " ")

Tuple:

tup = (1,2,3,7,8,9)
for i in range(len(lst)):
  print(lst[i],end = " ")

This is the entire content of this article.