0

How to create a list by concatenating two list using python

Var=['Age','Height']
Cat=[1,2,3,4,5]

My output should be like this below.

AgeLabel=['Age1', 'Age2', 'Age3', 'Age4', 'Age5']
HeightLabel=['Height1', 'Height2', 'Height3', 'Height4', 'Height5']
jotasi
  • 5,077
  • 2
  • 29
  • 51
user3762120
  • 256
  • 2
  • 12
  • 1
    Check out my recent answer, https://stackoverflow.com/a/48412769/901925. One or two list comprehensions will do the job nicely. – hpaulj Jan 24 '18 at 08:35
  • https://stackoverflow.com/questions/4344017/how-can-i-get-the-concatenation-of-two-lists-in-python-without-modifying-either – Douglas Jan 24 '18 at 08:41

5 Answers5

2

Combining a dict comprehension and a list comprehension:

>>> labels = 'Age', 'Height'
>>> cats = 1, 2, 3, 4, 5
>>> {label: [label + str(cat) for cat in cats] for label in labels}
{'Age': ['Age1', 'Age2', 'Age3', 'Age4', 'Age5'],
 'Height': ['Height1', 'Height2', 'Height3', 'Height4', 'Height5']}
Vincent
  • 12,919
  • 1
  • 42
  • 64
0

You can consider the second list elements as strings concatenate the strings by looping over both the lists. Maintain a dictionary to store the values.

Var=['Age','Height']
Cat=[1,2,3,4,5]
label_dict = {}
for i in var:
    label = []
    for j in cat:
         t = i + str(j)
         label.append(t)
    label_dict[i+"Label"] = label

at the end label_dict will be

  label_dict = {AgeLabel:['Age1', 'Age2', 'Age3', 'Age4', 'Age5'],HeightLabel:['Height1', 'Height2', 'Height3', 'Height4', 'Height5']}
sona
  • 96
  • 2
  • 14
0
Var=['Age','Height'] 
Cat=[1,2,3,4,5] 
from itertools import product 
print(list(map(lambda x:x[0]+str(x[1]),product(Var,Cat))))

This will give you the following output.

['Age1', 'Age2', 'Age3', 'Age4', 'Age5', 'Height1', 'Height2', 'Height3', 'Height4', 'Height5']

You can split the list as per your requirement.

Sneha
  • 140
  • 6
0

Simple and Concise.

Var=['Age','Height']
Cat=[1,2,3,4,5]

AgeLabel = []
HeightLabel= []

for cat_num in Cat:
    current_age_label = Var[0] + str(cat_num)
    current_height_label = Var[1] + str(cat_num)
    AgeLabel.append(current_age_label)
    HeightLabel.append(current_height_label)

print(AgeLabel)
print(HeightLabel)

Output

AgeLabel= ['Age1', 'Age2', 'Age3', 'Age4', 'Age5']
HeightLabel= ['Height1', 'Height2', 'Height3', 'Height4', 'Height5']
0

Try this:-

Var=['Age','Height']
Cat=[1,2,3,4,5]
for i in Var:
    c = [(i+str(y)) for y in Cat]
    print (c)  #shows as you expect
Narendra
  • 1,511
  • 1
  • 10
  • 20