1

I have a list of names like this:

['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover',....]

And a list of date-times:

[datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17),.....]

now I'm trying to add them together in between of each other like this in a new list:

[('Albert Einstein', datetime.date(1879, 3, 14)),...

Nothing I tried seem to work. It also doesn't seem possible to me with append or extend, hope someone can help me.

HerooCoder
  • 19
  • 7

3 Answers3

1

Use zip(a, b) for the two lists, e.g.

a = [1, 2, 3]
b = ["a", "b", "c"]
print(list(zip(a, b)))

[(1, "a"), (2, "b"), (3, "c")]
lorg
  • 1,160
  • 1
  • 10
  • 27
1

As mentioned in the comments you can simply use zip which can take lists as parameters and returns an iterator, with tuples of i-th position of the lists passed as arguments, therefore if we try to print it, we'll get a zip object at ... that's why we need to use list() so we can access the values in a list format:

import datetime
people = ['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover']
dates = [datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17)]
output = list(zip(people,dates))

For example:

[('Albert Einstein', datetime.date(1642, 12, 25)),
 ('Benjamin Franklin', datetime.date(1879, 3, 14)),
 ('J. Edgar Hoover', datetime.date(1706, 1, 17))]
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
0

Try this:

names = ['Albert Einstein', 'Benjamin Franklin', 'J. Edgar Hoover']
dates = [datetime.date(1642, 12, 25), datetime.date(1879, 3, 14), datetime.date(1706, 1, 17)]

print(list(zip(names, dates)))

Output:

[('Albert Einstein', datetime.date(1642, 12, 25)), ('Benjamin Franklin', datetime.date(1879, 3, 14)), ('J. Edgar Hoover', datetime.date(1706, 1, 17))]
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53