2

Given two lists, both having String elements, write a python program using python lists to create a new string as per the rule given below:

The first element in list1 should be merged with last element in list2, second element in list1 should be merged with second last element in list2 and so on. If an element in list1/list2 is None, then the corresponding element in the other list should be kept as it is in the merged list.

Sample Input:

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']  

Expected Output:

“An apple a day keeps the doctor away”

My code:

 for i,j in range(n,len(list1)):
     a = 1
     j = n - a
     s = list[i]+list[j]
     resultant_data.append(s)
     a=+1 
     n+=1

    return resultant_data

#Provide different values for the variables and test your program
list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
merged_data=merge_list(list1,list2)
print(merged_data)
 Traceback (most recent call last):
  line 21, in <module>
    merged_data=merge_list(list1,list2)
  line 8, in merge_list
    for i,j in range(n,len(list1)):
 TypeError: 'int' object is not iterable
ZF007
  • 3,708
  • 8
  • 29
  • 48

6 Answers6

1

list is a reserved keyword, I think this should be the correct snippet.

 for i,j in range(n,len(list1)):
     a = 1
     j = n - a
     s = list1[i]+list2[j]
     resultant_data.append(s)
     a=+1 
     n+=1
yodebu
  • 167
  • 12
1

If you want to iterate on your two lists, you can use built-in functions of Python:

words = []
for elt0, elt1 in zip(list1, reversed(list2)):
    w = elt0
    if elt1:
       w += elt1
    words.append(s)
return " ".join(words)
Guillaume
  • 11
  • 3
  • 1
    explains the actual problem. – yodebu Jul 25 '19 at 11:44
  • 1
    You can't do this as there is None in the list2 –  Jul 25 '19 at 12:23
  • You are right, the addition line does not work with `None`. My point was just to simplify the iteration and not to deal with the concatenation problem. bharatk did the full for loop. I will correct my answer – Guillaume Jul 25 '19 at 13:11
1

The or operator is good for coalescing None into an empty string. map for applying a function to the two lists. lambda for creating a simple function in-line, join for merging the elements separated by spaces..

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n'] 

print(' '.join(map(lambda x, y: (x or '')+(y or ''),list1, list2[::-1])))

An apple a day keeps the doctor away
Deepstop
  • 3,627
  • 2
  • 8
  • 21
  • The question asks for a list, but the expected output is a string. Change `' '.join` to `list` to print a list instead of a string. – Deepstop Jul 25 '19 at 09:57
1

your iterating over 2 indexes, so you need 2 ranges (iterable objects).

something like:

def merge_list(list1, list2):
    resultant_data = []
    list2.reverse()

    for i,j in zip(range(0, len(list1)), range(0, len(list2))):
        if list2[j] is not None:
            s = list1[i]+list2[j]
        else:
            s = list1[i]
        resultant_data.append(str(s))

    return ' '.join(resultant_data)

#Provide different values for the variables and test your program
list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
merged_data=merge_list(list1,list2)
print(merged_data)

See also https://discuss.codecademy.com/t/loop-two-variables-simultaneously-in-python-3/261808/7

I also removed the computation of the index for list2, if you just reverse the list to begin with, you can just loop over it like you do with list1

There's still some room for improvement, eg. if list1 also contains None values, you need extra checks...


Some more info after comments: in python3 the range function returns a range object instead of a list (python2)(cfr. Python 3 range Vs Python 2 range) But when you use it for iteration this doesn't make a difference:

    Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
    >>> list1=['a','b']
    >>> range(0, len(list1))
    range(0, 2)
    >>> for i in range(0, len(list1)):
    ...     print(list1[i])
    ...
    a
    b

The code I entered above gave the same error TypeError: 'int' object is not iterable in python3

The problem is that you want to iterate over 2 things and only provide 1 iterable cfr. object not iterable on treehouse and in this case the second iterable is not provided.

When you do not provide a second iterable , it will iterate over the only list you provide. So it will think (see example below) 0 is the first thing to iterate over and 1 is the second thing to iterate over, and 0 and 1 are ints and thus not iterable.

>>> for i,j in [0,1]:
...     print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> for i,j in [0,1],:
...     print i
...
0
Kim Paulissen
  • 578
  • 5
  • 5
  • this looks like the correct explanation of the error. @kim-paulissen this error looks specific to python2, where range produces a ranged list, what about python3 then, where range gives a lazy iterator? – yodebu Jul 25 '19 at 11:41
  • I update my answer above with some more info, since my comment was too long :-) – Kim Paulissen Jul 25 '19 at 12:32
0
  • reversed(seq) - in-built function of Python, it's return a reverse iterator.
  • strip() - in-built function of Python is used to remove all the leading and trailing spaces from a string.

Ex.

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']

string1 = ""
for a1,a2 in zip(list1,reversed(list2)):
    if a2 is not None:
        string1 = string1+" "+a1+a2
    else:
        string1 = string1+" "+a1

print(string1.strip())

O/P:

An apple a day keeps the doctor away
bharatk
  • 4,202
  • 5
  • 16
  • 30
0

You got that error because None is not a string as it does not consist of quotation marks like this "None". That's why it is considered an integer. And so an integer and a string cannot be concatenated. To avoid the error you need an if condition before the concatenation which checks if that index is None or not.

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
j = -1
sentence = ""
for i in list1:
    if list2[j] != None:
        word = i + list2[j]
    j-=1
    sentence = sentence + word + " "
print(sentence)