Home > Software engineering >  Appending lists together in a neat way
Appending lists together in a neat way

Time:11-30

My task right now is to append two list together. Of course I know that I can do:

Names = ["Samson", "Daniel", "Jason", "Delion"]
Ages = [16, 18, 34, 27]
Names.extend(age)

However, what i am attempting to do is print these lists in the format of:

Samson   16
Daniel   18
Jason    34
Delion   27

With my current attempt, all ive been able to do is print in the format:

Samson, Daniel, Jason, Delion, 16, 18, 34, 27

Greatly appreciated if I could get some sort of help on how to do this.

CodePudding user response:

You can use zip function.

names = ["Samson", "Daniel", "Jason", "Delion"]
ages = [16, 18, 34, 27]
new_list = list(zip(names, ages))
for name, age in new_list:
    print(f"{name}\t{age}")

CodePudding user response:

You can use a dictionary here.

Names = ["Samson", "Daniel", "Jason", "Delion"]
Ages = [16, 18, 34, 27]
a_dict = dict(zip(Names, Ages))
for key in a_dict.keys():
    print(key, a_dict[key])

CodePudding user response:

Names = ["Samson", "Daniel", "Jason", "Delion"]
Ages = [16, 18, 34, 27]

data = zip(Names, Ages)

for person in data:
    print(person[0], person[1])

CodePudding user response:

Use the zip function

Names = ["Samson", "Daniel", "Jason", "Delion"]
Ages = [16, 18, 34, 27]
for name, age in zip(Names, Ages):
    print(f"{name}\t{age}")
  • Related