Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Gregory Heard
Gregory Heard
1,975 Points

Adding two values from FOR loops

Hi Guys,

Going really strong on the course after python basics and enjoying it. I have suddenly become stuck by a seemingly simple challenge. Probably just having a mental block.

list_1 = [1,2,3,4,5]
list_2 = list("abcde")

What i want to do is combine the two iterables into a single list of tuples. Something like [(1, a), (2,b), (3,c)] etc.

I understand i have to iterate through list_1, but i am struggling at how to assign the same index to the second list.

Thanks in advance.

2 Answers

Haider Ali
.a{fill-rule:evenodd;}techdegree seal-36
Haider Ali
Python Development Techdegree Graduate 24,724 Points

Hi there Gregory, this is how i would go about doing the challenge; firstly, you need to create a new list to store your tuples in:

new_list = []

Next, its time to create the for loop. I would loop through list_1 and that at the beginning of the tuple, next i would use list_2[i-1] to get the corresponding value from list_2 since indexes start at 0 and I will be using i as my loop counter:

for i in list_1:
    new_list.append((i, list_2[i-1]))

If you have any further questions, please leave a comment :)



Hi Gregory, Haider Ali did a good explanation about a way to solve you problem! :smiley:

However, there is a easier and easier-to-understand way. The enumerate and zip functions can be very handy. Examples:

my_list = ["a", "b", "c"]

# Enumerate
for x, y in enumerate(my_list):
    print("{}: {}".format(x, y))

# This will print:

#   0: a
#   1: b
#   2: c

# Zip
my_second_list = ["d", "e", "f"]
for x, y in zip(my_list, my_second_list):
    print("{}: {}".format(x, y))

# This will print:

# a: d
# b: e
# c: f

You can solve your task by doing this:

list_1 = [1, 2, 3, 4, 5]
list_2 = list("abcde")
result_list = []

index = 0
for x, y in zip(list_1, list_2):
    result_list.append((x, y))
    index += 1


Hope that helps! ~xela888