johnnyr2233
johnnyr2233

Reputation: 77

creating new string with alternating elements in python

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

Upvotes: 0

Views: 78

Answers (3)

Narendra Kamatham
Narendra Kamatham

Reputation: 340

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')

Upvotes: 0

Divyesh patel
Divyesh patel

Reputation: 997

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']

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522331

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']

Upvotes: 0

Related Questions