-1

A simple list, that I want to loop through to print each element twice. Each time to add a different prefix. The output will be appended into a new list.

List1 = ["9016","6416","9613"]

The ideal result is:

['AB9016', 'CD9016', 'AB6416', 'CD6416', AB9613', 'CD9613']

I have tried below and but the output is:

new_list = []

for x in List1:
    for _ in [0,1]:
        new_list.append("AB" + x)
        new_list.append("CD" + x)

print (new_list)

['AB9016', 'CD9016', 'AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB6416', 'CD6416', 'AB9613', 'CD9613', 'AB9613', 'CD9613']

And I can't use:

new_list.append("AB" + x).append("CD" + x)

What's the proper way to do it? Thank you.

Mark K
  • 8,767
  • 14
  • 58
  • 118

6 Answers6

4

The problem is caused by the inner loop: the two appends will be called twice. Fixed code:

new_list = []

for x in List1:
    new_list.append("AB" + x)
    new_list.append("CD" + x)

Regarding chaining append calls: It would work if append returned the list (with the new item appended to it), but this is not the case, the append method returns None (doc).

kol
  • 27,881
  • 12
  • 83
  • 120
  • thank you for pointing out the problem. Glad to choose yours as the answer for its simplicity. – Mark K Jul 20 '20 at 14:02
4

Also could try an easy comprehension:

List1 = ["9016","6416","9613"]
result = [j+i for i in List1 for j in ('AB','CD')]
# ['AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB9613', 'CD9613']
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
2

The fastest method is to use the list comprehension. We are using 2 list comprehension to create the desired_list. Note that I also used the f string so I could easily ad the 'ABandCD` prefix.

list1 = ["9016","6416","9613"]
desired_list = [f'AB{x}' for x in list1] + [f'CD{x}' for x in list1]
print(desired_list)
Aleksander Ikleiw
  • 2,549
  • 1
  • 8
  • 26
2

I would use itertools.product for that task following way

import itertools
list1 = ["9016","6416","9613"]
prefixes = ["AB","CD"]
result = [x+y for y,x in itertools.product(list1,prefixes)]
print(result)

Output:

['AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB9613', 'CD9613']
Daweo
  • 31,313
  • 3
  • 12
  • 25
2

Here is a solution using itertools.product:

from itertools import product

lst1 = ['9016', '6416', '9613']
lst2 = ['AB', 'CD']

result = list(map(''.join, map(reversed, product(lst1, lst2))))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
1

we can use sum too:

In [25]: sum([[f'AB{i}',f'CD{i}'] for i in List1],[])
Out[25]: ['AB9016', 'CD9016', 'AB6416', 'CD6416', 'AB9613', 'CD9613']
Akhilesh_IN
  • 1,217
  • 1
  • 13
  • 19