For Loops w/ Strings & Lists
Both strings and lists are indexable, so we can access individual items by indicating an index with square brackets.
Examples:
print('Hello'[1]) # Should output letter 'e' at index of 1print(['Apple', 'Bananas', 'Kiwi', 'Strawberry'][2]) # Outputs KiwiExamples of indexing with a For Loop
# Using a for loop on a string with index
# NOTE: programmers often use single letters when creating an iterating variable
# I like to use i as "index"
phrase = 'Hello, World!'
size = len(phrase)
for i in range(size):
print('Current character at index', i, 'is:', phrase[i])Current character at index 0 is: H
Current character at index 1 is: e
Current character at index 2 is: l
Current character at index 3 is: l
Current character at index 4 is: o
Current character at index 5 is: ,
Current character at index 6 is:
Current character at index 7 is: W
Current character at index 8 is: o
Current character at index 9 is: r
Current character at index 10 is: l
Current character at index 11 is: d
Current character at index 12 is: !# Using for loop on a list of fruits via index
fruits = ['Apple', 'Banana', 'Kiwi', 'Strawberry']
print('The fruits in my blender:')
for i in range(len(fruits)):
print(' --', fruits[i])The fruits in my blender:
-- Apple
-- Banana
-- Kiwi
-- Strawberryrecall that
range()never includes the last valueindexing in Python always starts at 0(zero).
Therefore, a string of:
Hellohas its last character at index of 4, but has a length of 5Same idea applies to lists as well.
Accessing items in a String or a List without indexing
We can also just iterate through strings or lists by using a for loop without the need for the index values.
Last updated