0

Is it possible to add two lists, with different value types in Python? Or is there an alternative way? For example:

listString = ['a','b','c','d']
listInt = [1,2,3,4]

I want to combine these so that the output string is either: finalString = [('a',1),('b',2),('c',3),('d',4)] or finalString = ['a',1,'b',2,'c',3,'d',4]

UnknownM1
  • 13
  • 3

1 Answers1

0

Use zip:

listString = ['a','b','c','d']
listInt = [1,2,3,4]

list(zip(listString, listInt))
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

And itertools.chain or a nested list comprehension for the flattened version:

from itertools import chain
list(chain(*zip(listString, listInt)))
# ['a', 1, 'b', 2, 'c', 3, 'd', 4]

[x for pair in zip(listString, listInt) for x in pair]
# ['a', 1, 'b', 2, 'c', 3, 'd', 4]
user2390182
  • 72,016
  • 6
  • 67
  • 89