Lycon
Lycon

Reputation: 2499

Adding an item to a list from another list in python

I need to be able to add an item into list a from list b. The item from list b is to be added as soon as ' ' which is a double space is identified.

Therefore if the first item in the list is not a double space, then the loop goes on to check the next item in the list, if its also not a double space, it carries on until if finds the double space and then it replaces the first available double space with the item from list b. This should be looped so that if I run the function again, an item in list b is popped and added to the next available double space in list a.

a = ['a','c','e','j','h','  ','  ','  ','  ']
b = ['b','d','f','i','g']

x = 4
for item in a:
    if item == a[4]:
        break
if a[x] != '  ':
    a[x+1] = b.pop(-2)

else:
    a[x] = a[x+1]

print("list a: ",a)
print("List b: ",b)

Output:

list a:  ['a', 'c', 'e', 'j', 'h', 'i', '  ', '  ', '  ']
List b:  ['b', 'd', 'f', 'g']

That works, but I have a feeling my code doesn't work on all inputs. Does it? If it doesn't, what's wrong?

Upvotes: 0

Views: 587

Answers (5)

Andrew Clark
Andrew Clark

Reputation: 208725

I think this is what you are looking for:

def move_item(a, b):
    a[a.index('  ')] = b.pop()

>>> a = ['a','c','e','j','h','  ','  ','  ','  ']
>>> b = ['b','d','f','i','g']
>>> move_item(a, b)
>>> print('list a: ', a, '\nlist b: ', b)
list a:  ['a', 'c', 'e', 'j', 'h', 'g', '  ', '  ', '  ']
list b:  ['b', 'd', 'f', 'i']
>>> move_item(a, b)
>>> print('list a: ', a, '\nlist b: ', b)
list a:  ['a', 'c', 'e', 'j', 'h', 'g', 'i', '  ', '  ']
list b:  ['b', 'd', 'f']

Upvotes: 2

Density 21.5
Density 21.5

Reputation: 1930

I guess you want to do this:

[x.split(' ')[0] or b.pop() for x in a]

Upvotes: 0

cjm
cjm

Reputation: 3753

This:

a = [b.pop() if item == '  ' else item for item in a]

gets you:

['a', 'c', 'e', 'j', 'h', 'g', 'i', 'f', 'd']

Take a look at Python list comprehensions

Upvotes: 2

Rik Poggi
Rik Poggi

Reputation: 29322

Since this homework, I'm just going to give you some hints:

  1. You'll need to work with a indexes:

    for i in range(len(a)):
        if a[i] == ??? :
            a[i] = ??
    
  2. Why are you popping the -2th element? Check out what pop does.

Upvotes: 0

Reinstate Monica
Reinstate Monica

Reputation: 4723

You didn't ask a question, but here are some hints:

list.index, list.pop, a[index_of_doublespace] = popped_value_from_b

Upvotes: 0

Related Questions