jiii
jiii

Reputation: 13

Combining two lists one after another

I'm trying to combine lists to produce a result like this: [a, 1, b, 2, c, 3] but i can't get it to work. Can u tell me what's wrong/show me how to do it?

def newList(a, b):
    tmp = []
    tmp.append(zip(a, b))
    return tmp

a = ['a', 'b', 'c']
b = [1, 2, 3]

print(newList(a, b))

I get only zip object at 0x0449FE18 as a result.

Upvotes: 1

Views: 2838

Answers (4)

Ely Fialkoff
Ely Fialkoff

Reputation: 652

You do not need to use zip. Assuming both lists have the same amount of elements (as is in your question) you can do something as simple as

newList = list()
for i in range(len(a)):
    newList.append(a[i])
    newList.append(b[i])
print(newList)

if the lists are not the same size then you need to ask yourself some questions about ordering but you can do it as simple as

newList = list()
biggestList = len(a) if len(a) > len(b) else len(b)
for i in range(biggestList):
    if a[i]:
        newList.append(a[i])
    if b[i]:
        newList.append(b[i])
print(newList)

you can play around with this logic depending on what your criteria are for the list sizes and how to handle the order.

Upvotes: 0

strawdog
strawdog

Reputation: 208

>>> [x for y in zip(['a', 'b', 'c'],[1, 2, 3]) for x in y]
['a', 1, 'b', 2, 'c', 3]

Upvotes: 1

Sk.
Sk.

Reputation: 460

without imports

b = [1, 2]

a = ['a', 'b', 'c']

result = [item for a in map(None, a, b) for item in a][:-1]

['a', 1, 'b', 2, 'c']

important array "b" has one element less than array "a"

.

if has the same length

result = [item for a in map(None, a, b) for item in a]

['a', 1, 'b', 2, 'c', 3]

Upvotes: 0

chepner
chepner

Reputation: 530970

You need to flatten the sequence produced by zip. The easiest way to do that is using itertools.chain.from_iterable:

>>> from itertools import chain
>>> list(chain.from_iterable(zip(['a', 'b', 'c'], [1,2,3])))
['a', 1, 'b', 2, 'c', 3]

The class method from_iterable takes the iterable-of-iterables like [('a', 1), ('b', 2), ...], and turns it into a single iterable by extracting the elements from the subiterables one at a time, from left to right.

Upvotes: 2

Related Questions