-1

I have following two lists to combine. I'm trying to use zip() but header_list runs out for obvious reason.

header_list = ['1 mo', '3 mo', '6 mo', '1 yr', '2 yr', '3 yr', '5 yr', '7
yr', '10 yr', '20 yr', '30 yr']

data_list = [1.29, 1.44, 1.61, 1.83, 1.92, 2.01, 2.25, 2.38, 2.46,
2.64, 2.81, 1.29, 1.41, 1.59, 1.81, 1.94, 2.02, 2.25, 2.37, 2.44, 2.62, 2.78, 1.28, 1.41, 1.6, 1.82, 1.96, 2.05, 2.27, 2.38, 2.46, 2.62, 2.79]

The result should be a tuple in the following format:

('1 mo', 1.29)
('3 mo', 1.44)
('6 mo', 1.61)
('1 yr', 1.83)
('2 yr', 1.92)
('3 yr', 2.01)
('5 yr', 2.25)
('7 yr', 2.38)
('10 yr', 2.46)
('20 yr', 2.64)
('30 yr', 2.81)
('1 mo', 1.29)
('3 mo', 1.41)
('6 mo', 1.59)
('1 yr', 1.81)
('2 yr', 1.94)
('3 yr', 2.02)
('5 yr', 2.25)
('7 yr', 2.37)
('10 yr', 2.44)
('20 yr', 2.62)
('30 yr', 2.78)
...
cmaher
  • 5,100
  • 1
  • 22
  • 34
Hannan
  • 1,171
  • 6
  • 20
  • 39

3 Answers3

6

If you use itertools you can use cycle to repeat the shorter one:

from itertools import cycle
print(zip(cycle(header_list), data_list))

zip will stop once the shorter iterable ends. cycle returns an iterable that never ends (constantly repeats header_list), so data_list will be shorter (and it will stop zipping when data_list ends).

Bailey Parker
  • 15,599
  • 5
  • 53
  • 91
1

Assuming you want the shorter list to simply wrap, you can iterate over the indices of the longer list and mod the current index by the length of the shorter list:

out = [(header_list[i%len(header_list)], data_list[i]) for i in range(len(data_list))]

Or, to be more Pythonic:

out = [(header_list[i%len(header_list)], e) for i,e in enumerate(data_list)]
Niema Moshiri
  • 909
  • 5
  • 14
0

how about something like this?

counter = 0
new_list = []
for data in data_list:
    new_list.append([header_list[counter%len(header_list)],data])
    counter+=1
  • In general, using counters and `list.append` isn't very pythonic. In this instance, you'd definitely be better off constructing the list via a comprehension. If you do need to access an index, `enumerate` is your friend. – Bailey Parker Jan 20 '18 at 01:27
  • @BaileyParker `list.append` is *perfectly pythonic*, although you are correct, here `enumerate` is what you would use instead of a counter variable. Better yet, though, it would be `zip` – juanpa.arrivillaga Jan 20 '18 at 01:33