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']
2

5 Answers 5

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']}
Sign up to request clarification or add additional context in comments.

Comments

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']}

Comments

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.

Comments

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

Comments

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.