Adding the string of two list and store it in a new list

Viewed 70
listA = ["A","B","C"]
listB = ["a","b","c"]

It's okay to write

listC = [listA[0]+listB[0], listA[1]+listB[1],listA[2]+listB[2]]

But when I write

i=0
listD = []
while i < len(listA):
        listD[i] = listA[i]+listB[i]
        i+=1

or

i=0
listD = []
while i < len(listA):
        listD[i] = str(listA[i])+str(listB[i])
        i+=1

It's not okay. PLease tell me why and how to correct it. Many thanks!!

5 Answers

You can use zip as @Rakesh suggested, but let me explain why your code does not work.

It would work if you did the following:

i=0
listD = []
while i < len(listA):
        listD.append(listA[i]+listB[i])
        i+=1

You cannot assign to list[x] to create a new item in the list. That is the syntax for modifying existing items. To add new items, use append.

Use zip with list comprehension.

Ex:

listA = ["A","B","C"]
listB = ["a","b","c"]

print([i+v for i,v in zip(listA, listB)])

Output:

['Aa', 'Bb', 'Cc']

Instead of using a loop you could use something like this.

listA = ["A","B","C"]
listB = ["a","b","c"]
[x+y for x,y in zip(listA,listB)]
# zip will output something like this [('A','a'),('B','b'),('C','c')]

This is because you are trying to assign a value on the index which does not exist.

Python does not allow this. Instead you can try this.

i=0
listD = []
while i < len(listA):
    listD.append(listA[i]+listB[i])
    i+=1

Comment for any doubt.

HII, what mistake you are doing is,listD is an empty list but you are accessing with index,So its not possible to assign a value by index for an empty list

Try this,

listA = ["A","B","C"]
listB = ["a","b","c"]
print map(lambda x,y:x+y,listA,listB)

Result:['Aa', 'Bb', 'Cc']
Related