List comprehension/python

I’m practicing using the list data type and I’m interested in one of the results from an exercise.
The exercise provides two lists:

list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]

and asks you to write code that returns the following list of tuples:

['My', 'name', 'is', 'Kelly']

I initially wrote this with the zip() method:

list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
list3 = zip(list1,list2)

result = list(list3)

And it returned: [('M', 'y'), ('na', 'me'), ('i', 's'), ('Ke', 'lly')]

With list comprehension:

list1 = ["M", "na", "i", "Ke"]

list2 = ["y", "me", "s", "lly"]

list3 = [i+j for i, j in zip(list1, list2)]


It returns the expected solution:['My', 'name', 'is', 'Kelly']

I think I understand why list comp. does this in the other method not…I think list comprehension includes the solution within a list framework as opposed to the previous attempt which breaks the code into parts and, in turn, presents the content in parts. There isn’t a fluid connection between operation (not as much as when they are all included within (what I call) the list framework–> the code within brackets

Am I on the right track?

It’s this part of the list comprehension that concatenates the strings into a single string. zip() by itself doesn’t have this. Not something specific to the list comprehnsion in that you could get the same resulting using a for loop.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.