-2

I am new to python and am trying to create a new list from 2 other lists by appending each item in the list.

for number in num:

    for names in name:

        print(number+names)


num = [1,2,3,4,5]

name = ['Tom','Bob','Dave']

new_desired_list = [1Tom,1Bob,1Dave,2Tom,2Bob,2Data,3Tom,3Bob,3Dave..etc]
tituszban
  • 4,797
  • 2
  • 19
  • 30
TB_new
  • 9
  • 1
  • 1

3 Answers3

3

Seems like you want the cartesian product of both lists. For that you have itertools.product. In order to join the strings you could use string formatting:

from itertools import product

[f'{i}{j}' for i,j in product(num, name)]
# ['{}{}'.format(i,j) for i,j in product(num, name)] # for Python 3.6< 
# ['1Tom', '1Bob', '1Dave', '2Tom', '2Bob'...
yatu
  • 86,083
  • 12
  • 84
  • 139
1

You could try appending a list ;)

l = []

numbers = [1,2,3,4,5]

names = ['Tom','Bob','Dave']

for number in numbers:
    for name in names:
        l.append(str(number) + str(name))

print(l)
tituszban
  • 4,797
  • 2
  • 19
  • 30
0

Use list comprehension:

new_list = [str(i)+x for i in num for x in name]

Example:

>>> num = [1,2,3,4,5]
>>> name = ['Tom','Bob','Dave']
>>> 
>>> new_list = [str(i)+x for i in num for x in name]
>>> new_list
['1Tom', '1Bob', '1Dave', '2Tom', '2Bob', '2Dave', '3Tom', '3Bob', '3Dave', '4Tom', '4Bob', '4Dave', '5Tom', '5Bob', '5Dave']
>>> 
Nouman
  • 6,947
  • 7
  • 32
  • 60