Python: Strings

Hi I just wanted to know what the range(len(word)) part does exactly? For both Strings and Lists. Thank you!

for i in range(len(word)):
if i % 2 == 0:
print(word[i])

range(len(word)) uses two concepts: len() and range().


The len() function returns the length of an object, be that a string, iterable, etc.

Example
>>> len("abc")
3
>>> lst = [0, 1, 2, 3, 4]
>>> len(lst)
5

Here, you can see that len() will return the number of characters in a string and the number of elements in a list.


range() creates an object of type range and can be used to help iterate (or loop) over a string or iterable. It takes in either one argument (stop), two arguments (start, stop and where step defaults to a value of 1) or three arguments (start, stop, step).

Example
>>> for i in range(5):
...    print(i)
...
0
1
2
3
4
>>> for i in range(3, 5):
...    print(i)
...
3
4
>>> for i in range(0, 10, 2):
...    print(i)
...
0
2
4
6
8

Now, the question is how do they work together? Let’s say we wanted to print out every other element in a list. We would use range() with a start of 0 and step of 2. What about stop? We have to stop iterating over the list after we’ve looped over the last element. Otherwise, we would get an IndexError because we tried to access an element at an index that doesn’t exist.

Example
fruits = ["apple", "banana", "cherry", "date", "elderberry", "fig"]

for i in range(0, len(fruits), 2):
    print(fruits[i])

Output

apple
cherry
elderberry

More on len() here and range() here.

3 Likes