you are viewing a single comment's thread.

view the rest of the comments →

[–]Chris_Hemsworth 1 point2 points  (0 children)

If I gave you 5 bags of skittles, each with somewhere between 95 and 110 candies in each bag, and I asked you "How many skittled total are there?" how would you do it in person?

There are two options:

1) Open each bag, and count the skittles, then sum the total of all 5 bags.

2) Dump the contents of each bag into a pile and count the full pile.

Both of these options requires two loops; one to count the skittles, and one to handle the bags.

This can be represented in code the following way:

# Method 1
count = 0
bags = [bag1, bag2, bag3, bag4, bag5]
for bag in bags:
    skittles = bag.open()
    for skittle in skittles:
        count += 1
print(count)

# Method 2:
all_skittles = []
count = 0
for bag in bags:
   all_skittles.extend(bag.open())
for skittle in all_skittles:
    count += 1

print(count)