-4

please explain this part of the code

rollNumber[:]=[items for items in rollNumber if items in sampleDict.values()]

This is the complete code

rollNumber  = [47, 64, 69, 37, 76, 83, 95, 97]
sampleDict  ={'Jhon':47, 'Emma':69, 'Kelly':76, 'Jason':97} 

print("List -", rollNumber)
print("Dictionary - ", sampleDict)

rollNumber[:] = [item for item in rollNumber if item in sampleDict.values()]
print("after removing unwanted elemnts from list ", rollNumber)
Rajith Thennakoon
  • 3,975
  • 2
  • 14
  • 24
JacksonPro
  • 3,135
  • 2
  • 6
  • 29

5 Answers5

1
rollNumber[:] = [item for item in rollNumber if item in sampleDict.values()]

For each of the value in the for loop, which satisfies the if condition, is getting added to the list rollNumber.

Stan11
  • 274
  • 3
  • 11
1

To put it simple, it is a shorthand for following codes

tempRollNumber = []

for item in rollNumber:
    if item in sampleDict.values():
        tempRollNumber.append(item)

rollNumber = tempRollNumber
1

Not sure what the [:] means for rollNumber[:]. But this line of code here

[item for item in rollNumber if item in sampleDict.values()]

is setting the variable rollNumber equal to a list of things where all the items from rollNumber that match a value from the sampleDict are in the new list.

It can be expanded to this block here to understand what is going on.

temproll = []
for item in rollNumber:
    if item in sampleDict.values():
        temproll.append(item)
1
rollNumber[:] = [item for item in rollNumber if item in sampleDict.values()]

This line of code does an element by element comparison between the elements of list rollNumber and sampleDict dictionary's values (Not keys, but values).

If rollNumber[i] == sampleDict.values()[i], then that value is written in the rollNumber list (called inplace replacement ) and if match isn't found then that value isn't written... hence eventually you get just the matched set of values.

1

Several answers have explained the right-hand side of the assignment but nobody has explained the use of [:] on the left-hand side.

I am lazy, so I'll just link to an existing answer for that: What is the difference between slice assignment that slices the whole list and direct assignment?

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15