Vogelsire
Vogelsire

Reputation: 189

Joining 2 list of different size in Python

I get "list of index out of range" error when try to use 2 different size list.

example:

ListA = [None, None, None, None, None]
ListB = ['A', None, 'B']

for x, y in enumerate(ListA):
    if ListB[x]:
        ListA[x]=ListB[x]

Doing this will get "list of index out of range" error, because ListB[3] and ListB[4] does not exist:
I hope to join ListA and ListB to get ListA look like this:

ListA = ['A', None, 'B', None, None]

How can I achieve that?

Upvotes: 2

Views: 2530

Answers (5)

Adem Öztaş
Adem Öztaş

Reputation: 21466

Try this:

>>> [i[1] for i in map(None,ListA,ListB)]
['A', None, 'B', None, None]

Upvotes: 2

Shankar
Shankar

Reputation: 866

Use MAP to avoid list index out of range error

for iterator,tup in enumerate(map(None,ListA,ListB)):
    if tup[1]:
        ListA[iterator] = tup[1]

This will fix the issue.

Upvotes: 1

Abhijit
Abhijit

Reputation: 63757

The fastest solution is to use slice assignment

>>> ListA = [None, None, None, None, None]
>>> ListB = ['A', None, 'B']
>>> ListA[:len(ListB)] = ListB
>>> ListA
['A', None, 'B', None, None]

Timing

>>> def merge_AO(ListA, ListB):
    return [ i[1] for i in map(None,ListA,ListB)]

>>> def merge_ke(ListA, ListB):
    for x in range(len(ListB)): #till end of b
        ListA[x]=ListB[x]
    return ListA

>>> def merge_JK(ListA, ListB):
    ListA = [b or a for a, b in izip_longest(ListA,ListB)]
    return ListA

>>> def merge_AB(ListA, ListB):
    ListA[:len(ListB)] = ListB
    return ListA

>>> funcs = ["merge_{}".format(e) for e in ["AO","ke","JK","AB"]]
>>> _setup = "from __main__ import izip_longest, ListA, ListB, {}"
>>> tit = [(timeit.Timer(stmt=f + "(ListA, ListB)", setup = _setup.format(f)), f) for f in funcs]
>>> for t, foo in tit:
    "{} took {} secs".format(t.timeit(100000), foo)


'0.259869612113 took merge_AO secs'
'0.115819095634 took merge_ke secs'
'0.204675467452 took merge_JK secs'
'0.0318886645255 took merge_AB secs'

Upvotes: 3

kelvin
kelvin

Reputation: 149

try this:

ListA = [None, None, None, None, None]
ListB = ['A', None, 'B']

for x in range(len(ListB)): #till end of b
    ListA[x]=ListB[x]

Upvotes: 1

Janne Karila
Janne Karila

Reputation: 25207

Use itertools.izip_longest

from itertools import izip_longest
ListA = [b or a for a, b in izip_longest(ListA,ListB)]

Upvotes: 8

Related Questions