Lists and Loops

The code below shows some ways of using python lists (known as arrays in many languages). Note how these lists are "sliced" from index i to j using my_list[i:j] notation.

How to print a list structure

my_list = [1, 2, 3, "a", "b", "c"] print("my_list is:", my_list)

my_list is: [1, 2, 3, 'a', 'b', 'c']

Prints each element of a list individually

print("Looping through a list...")
    for item in my_list:
    print("item is", item)
Looping through a list...
item is 1
item is 2
item is 3
item is a
item is b
item is c

Using range to loop through a list by index

print("A less great way to loop through a list...")
    for index in range(len(my_list)):
    item = my_list[index] # accessing an element in a list! print("item is", item)

A less great way to loop through a list...
item is 1
item is 2
item is 3
item is a
item is b
item is c

List slicing

Looping through a partial list

print("Slicing a list from beginning...") 
    for item in my_list[:3]: 
    print("item is", item)
item is 1
item is 2
item is 3

Looping through a partial list again

print("Enumerating a list...") 
    for i, item in enumerate(my_list):
    print("item number", i, "is", item)
Slicing a list to the end...
item is 1
item is 2
item is 3
item is a
item is b
item is c

print("Another way to enumerate using a list 'method'...")
for item in my_list: 
     index = my_list.index(item)
     print("item", item, "has index", index)
Another way to enumerate using a list 'method'...
item 1 has index 0
item 2 has index 1
item 3 has index 2
item a has index 3
item b has index 4
item c has index 5

Last updated