How do i combine these 2 lists together?

Is there a way to combine two lists together so the output is like this?
Would there be a way to make put Name and Age together so the list would look like Combined?

name = ["Joe", "Peter", "Max"] Age = [23, 26, 45] Combined = [["Joe", 23], ["Peter", 26], ["Max", 45]]
1 Like

The closest way I know of doing this is to use the zip() function. It will return a list of tuples containing combined elements from both lists. Like so:

name = ["Joe", "Peter", "Max"]
age = [23, 26, 45]
combined = list(zip(name, age))
print(combined)

The resulting output will look like this:

[('Joe', 23), ('Peter', 26), ('Max', 45)]

The zipped object needs to be converted to the list by using list() to get the output of a list.

2 Likes
name = ["Joe", "Peter", "Max"]
age = [23, 26, 45]
combined = [list(entry) for entry in zip(name, age)]
print(combined)

Output: [['Joe', 23], ['Peter', 26], ['Max', 45]]
2 Likes

Thank you for the answer, easy to understand :smile:

Thank you for the answer, could you explain what “entry” means? :grin:

It is just a variable. Nothing special about the word entry. You could pick a different and better name for the variable. e.g.

combined = [list(person) for person in zip(name, age)]

# or you could do:

combined = [list(x) for x in zip(name, age)]

Just pick a name which makes for better readability. entry isn’t the best word choice.

Have a look at a couple of Codecademy articles:
https://www.codecademy.com/article/list-comprehension
https://www.codecademy.com/article/zip-for-lists

1 Like

Ah i understand now, thanks!

1 Like