Let's say I have two lists
listA = ['a', 'b' , 'q' , 'y' , 'r']
listB = ['p', 'y' , 't' , 'h', 'a' , 'w', 'n']
Then I want to compare both listA
and listB
with each other and
Then update listA
as
listA = [0 , 'b' , 'q' , 0 , 'r']
the replaced value could be 0
or '0'
or any other value of my choosing
.
I am totally new to programming by the way.
But what I have tried is
if any(x in listA for x in listB):
listA[x] = 0
but the result i am getting is
listA = [0 , 0 , 0 , 0 , 0 ]
or first n items of listA
becomes 0
where n = length of listB
Thanks for your help.
Regards,
Dr. Tree
Tried:
if any(x in listA for x in listB):
listA[x] = 0
Expecting:
listA = [0,'b','q',0,'r']
CodePudding user response:
You can use a list comprehension to recreate the list.
listA = [0 if x in listB else x for x in listA]
CodePudding user response:
Definitely not the best answer, but some useful info for anyone confused as to why the OP does not work.
Couple of things to remember here:
listA[x] = 0
is a single assignment operation. If you want to be able to replace a finite amount of list elements with some value, then you will need the same number of assignment operations. Put another way, each element to be replaced needs to be reassigned.listA[x]
is a the reference to the value fromlistA
at indexx
, wherex
is a variable (therefore, the index is determined by the value ofx
). This is easily confused with the index of the element inlistA
that you want to replace. Put another way, if you want to replace the 1st (at index0
) element oflistA
, that has a previous value of say5
, you reassignlistA[0]
, notlistA[5]
.
Here is a workable solution (with comments) for what you want:
listA = ['a', 'b' , 'q' , 'y' , 'r']
listB = ['p', 'y' , 't' , 'h', 'a' , 'w', 'n']
# Loop over every element from listB
for elB in listB:
# For each one, loop over every element in listA (for comparison).
# This uses "enumeration" so we have the index of each element
# in `i` for when we need to do any re-assignment.
for i, elA in enumerate(listA):
# If the element from listB is a member of listA, replace
# the element from listA with `0`.
if elA == elB:
listA[i] = 0
print(listA) # [0, 'b', 'q', 0, 'r']
There are some more elegant ways to do this in Python, but this "exploded" view gives you a good understanding of what is going on.
Some cases to consider:
- Are any of these elements duplicated? In which lists?
- Could the elements being replaced have the same value as the one with which you are replacing? ...and so on.