-2

Is it possible to concatenate lists in python like this: line 1 from list A with line 1 from list B making a new line without any space between it, line 2 from list A with line 2 from list B, and so on?

Example:

A = ["AAA", "CCC" , "EEE"]
B = ["BBB", "DDD", "FFF"]

So the output would be:

C = ["AAABBB" , "CCCDDD" , "EEEFFF"]

I tried this code:

c = A + B

But I get a different output:

C = ["AAA", "CCC" , "EEE" , "BBB", "DDD", "FFF"]
mixelsan
  • 5
  • 4
  • 1
    Yes it's possible. Try using [`zip()`](https://docs.python.org/3.3/library/functions.html#zip) and come back here if you get stuck. Should be pretty straightforward though, especially if you look up examples. – Random Davis Oct 09 '20 at 16:52

4 Answers4

1

If the length of A and B is the same you can use list comprehension:

C = [A[i] + B[i] for i in range(len(A))]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

Try this :

C = [i + j for i, j in zip(A, B)] 
C

Source : https://www.geeksforgeeks.org/python-concatenate-two-lists-element-wise/

Subasri sridhar
  • 809
  • 5
  • 13
0

You try this with zip() it might be useful for your future code works.

A = ["AAA", "CCC" , "EEE"]
B = ["BBB", "DDD", "FFF"]

#List comprehension

output = [a+b for a,b in zip(A,B)]
print(output)

#Using for loop without list comprehension
for a,b in zip(A,B):
    print(a+b)
    #append :)
Ice Bear
  • 2,676
  • 1
  • 8
  • 24
0
A = ["AAA", "CCC" , "EEE"]
B = ["BBB", "DDD", "FFF"]

C = []

for i in range(len(A)):
    C.append(A[i] + B[i])

print(C)

This too works. Hope it helped you!

Pro Chess
  • 831
  • 1
  • 8
  • 23
  • Dont you think, saying `range(3)` will become invalid, when items in list is increased? Better to use `range(len(A))`, assuming both list are same size. – Delrius Euphoria Dec 12 '20 at 06:52