Previous Lesson Current Lesson Next Lesson

# Question 1

for x in [1, 2, 3, 4, 5]:
print(x)
print(x + 1)


This will output:

1
2
2
3
3
4
4
5
5
6


As the problem states, for each value of x, we output itself and itself added to 1, hence why we get two numbers for each iteration.

# Question 2

l = []

for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(x)
l.append(2 * x)


This will output:

1
2
3
4
5
6
7
8
9
10


The list will look like:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


For each value of x, we print out its value and append it multiplied by 2 to a list, so we build a list of 10 elements, which comprise the original elements (the numbers 1 through 10) multiplied by 2.

# Question 3

For each value of x in our tuple, it can create a pair with all other elements in that same tuple, except for the one where x is equal to itself (all elements are unique, so this is safe to do in this problem).

Thus, we need to have a double for loop, which is where we have to one for loop for iterating through x and a second for loop for a subsequent iteration variable y that adds the last element in a possible pair with x, where x != y.

This might motivate us to do something like this:

t = ("a", "b", "c")
template = "Pair: {}, {}"

for x in t:
for y in t:
if x != y:  # x can't equal itself
print(template.format(x, y))


However, if you run this, you’ll see that all of the pairs show up exactly twice!

To avoid this, the key is to have the second iterator y only iterate through elements that come after x in the tuple. For example, after we have paired "a" with "b", in the next iteration, where x = "b", we don’t need to start at "a" because we already have that pair. We skip "b" because the two number letters in the pair must be unique. Thus, the first next valid pair element is "c", which you see comes after x = "b".

Thus, instead of iterating over the elements of x, we can iterate through the indices of the tuple instead:

t = ("a", "b", "c")
indices = [0, 1, 2]
template = "Pair: {}, {}"

for x in indices:
for y in indices:
if y > x:  # only work with indices after 'x'
print(template.format(t[x], t[y]))


This problem really combines a lot of different topics: string interpolation, tuple (or collection) indexing, and if statements! This is certainly an example to go over more than once and is an excellent cumulative review of previous lessons.