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 1
print(['Apple', 'Bananas', 'Kiwi', 'Strawberry'][2]) # Outputs Kiwi

Examples 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])
# 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])
  • recall that range() never includes the last value

  • indexing in Python always starts at 0(zero).

  • Therefore, a string of: Hello has its last character at index of 4, but has a length of 5

  • Same 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.

# For loop on string

phrase = 'Hello, World!'

for character in phrase:
    print('Current Character:', character)
# For loop on list

fruits = ['Apple', 'Banana', 'Kiwi', 'Strawberry']

for fruit in fruits:
    print('Current fruit:', fruit)

Last updated