bugbytes
bugbytes

Reputation: 335

Adding the same elements into a list

how do I add the same elements into a list?

say

A= [2,3,4,4]
B= [2,4,4,5,7,6,7]

for i in B:
    if i ==4:
        B.remove(4)
        A.append(4)

        print B
        print A

When I did this, it removes all the 4s in list B but A is only added with one 4. How can I make it such that all the fours in B will go to A?

Upvotes: 0

Views: 104

Answers (3)

Dman2
Dman2

Reputation: 740

The following works for me:

A = [2, 3, 4, 4]
b = [2,4,4,5,7,6,7]
B=b[::]  # Create a copy so we don't edit the 'B' list we want to iterate over.
for i in B:
    if i==4:
        A.append(i)
        b.remove(i)

B = b[::]

print "B =",B
print "A =",A

This gives:

B = [2, 5, 7, 6, 7]
A = [2, 3, 4, 4, 4, 4]

Edit: Sorry, I got the 'A' list incorrect when I first posted!

Upvotes: 0

falsetru
falsetru

Reputation: 368924

Modifying the list whiling iterating over it is not recommeded.

>>> A = [2,3,4,4]
>>> B = [2,4,4,5,7,6,7]
>>> 
>>> A.extend([4] * B.count(4))
>>> B = [x for x in B if x != 4]
>>> A
[2, 3, 4, 4, 4, 4]
>>> B
[2, 5, 7, 6, 7]

Upvotes: 2

hamon
hamon

Reputation: 1016

If I run your script, I get the following output

[2, 4, 5, 7, 6, 7]
[2, 3, 4, 4, 4]

There is only one 4 deleted from B because you removed an element while running over the list. Maybe you should remove the 4's from B after looping over B.

A = [2,3,4,4]
B = [2,4,4,5,7,6,7]

for i in B:
    if i == 4:
        A.append(4)
B = filter(lambda a: a != 4, B)
print B
print A

Upvotes: 1

Related Questions