0

I need to make a new list that contains alternating elements from the two list from before. example: listA = "a","b","c" listB= "A","B","C" the output should be "a","A","b","B","c","C"

def one_each(lst1,lst2):
        newList=[]
        for i in range(len(lst2)):
              newList.append(lst1[i])
              newList.append(lst2[i])
        return newList
1
  • 4
    it.chain.from_iterable(zip(a,b)) Commented Oct 31, 2019 at 3:31

3 Answers 3

1

you have to use small length list to reiterate so, add if condition to get your length
try this one:

def one_each(lst1,lst2):
  iRange=len(lst1)
  if len(lst2)<iRange:
    iRange=len(lst2)
  newList=[]
  for i in range(iRange):
        newList.append(lst1[i])
        newList.append(lst2[i])
  return newList

print (['a','b','c'],['A','B','C','D'])

output:

['a', 'A', 'b', 'B', 'c', 'C', 'c']
Sign up to request clarification or add additional context in comments.

7 Comments

The lists are different sizes
then use small size list to iterate
BTW if A has 3 element and B has 5 then last 2 element of new list must be non alternative is it like that ?
once A is done and its finished alternating, the extras for B shouldnt show
can you please update your question and add your error pron code on post or your tested sample data
|
0

Try using a single loop over the index range of one of the two lists, then append an element from each list at each iteration.

def one_each(lst1, lst2):
    lst = []
    for i in range(0, len(lst1)):
        lst.append(lst1[i])
        lst.append(lst2[i])
    return lst

lst1 = ['a', 'b', 'c']
lst2 = ['A', 'B', 'C']

output = one_each(lst1, lst2)
print(output)

This prints:

['a', 'A', 'b', 'B', 'c', 'C']

Comments

0

Try this

I've used zip and concate all the elements.

listA = ["a","b","c"]
listB= ["A","B","C"]
print reduce(lambda x,y:x+y,zip(listA, listB))

Result: ('a', 'A', 'b', 'B', 'c', 'C')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.