Reputation: 87
I have two lists in the next code snippet:
lst1 = ['a','b','c','d']
lst2 = [1,2,3,4]
I'm willing to loop over the second list while using the first and get the following:
'a','b','c','d'
'a','b',1,'c','d'
'a','b',1,2,'c','d'
'a','b',1,2,3,'c','d'
'a','b',1,2,3,4,'c','d'
how am I able to do this using a for loop?
Thanks
Upvotes: 0
Views: 58
Reputation: 23500
Damn, beaten by the bell. The following is a short-cut, it will not iterate over the list in the way you'd want it to (making it a bit faster). use this is possible:
list1 = ['a','b','c','d']
list2 = [1,2,3,4]
list1 = list1[:2] + list2 + list1[2:]
If you need to iterate over the list, and you want to preserve lines of code as well as memory usage, iterate over the second list and just add it within the first list:
a = ['a','b','c','d']
b = [1,2,3,4]
for i in range(0, len(b)-1):
a = a[:2+i] + [b[i]] + a[-2:]
The results will be:
['a', 'b', 1, 2, 3, 'c', 'd']
Upvotes: 1
Reputation: 23261
A lot of funny slice syntax, pretty straightforward. Probably some boundary condition (odd count of l1) should be verified.
def yield_from_l1_l2(l1, l2):
HALF_OF_L1 = len(l1) / 2
for i in xrange(len(l2)+1):
yield l1[:HALF_OF_L1] + l2[:i] + l1[HALF_OF_L1:]
l1 = ['a', 'b', 'c', 'd']
l2 = [1, 2, 3, 4]
for l in yield_from_l1_l2(l1, l2):
print l
Output:
['a', 'b', 'c', 'd']
['a', 'b', 1, 'c', 'd']
['a', 'b', 1, 2, 'c', 'd']
['a', 'b', 1, 2, 3, 'c', 'd']
['a', 'b', 1, 2, 3, 4, 'c', 'd']
Upvotes: 2
Reputation: 7517
What you are asking isn't absolutely clear; do you want something like that:
for i in range(len(b)+1):
tmp = []
for j in range(len(a)):
if j==2:
tmp += b[:i]
tmp.append( a[j] )
print tmp
or better:
for i in range(len(b)+1):
print a[:2] + b[:i] + a[2:]
Upvotes: 1