Python-Confused in list comprehension-:

  • Context: Python 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
  • Tags Tags
    List
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 1K views
shivajikobardan
Messages
637
Reaction score
54
I want to find difference between two list. I came across sth called list comprehension. I can't tell you how confused I am with this.

Code:
# Python 3 code to demonstrate
# to remove elements present in other list
# using list comprehension

# initializing list1
list1 = [1, 3, 4, 6, 7]

# initializing list2
list2 = [3, 6]

# printing list1
print("The list1 is : " + str(list1))

# printing list2
print("The list2 is : " + str(list2))

# using list comprehension to perform task
res = [i for i in list1 if i not in list2]

# printing result
print("The list after performing remove operation is : " + str(res))

My confusion lies here-:

Code:
res = [i for i in list1 if i not in list2]

What is happening here? I can't understand a single word. How to understand this please guide me.

Also can you guide a link to how to write latex in this site(how to write math? I am familiar with stackexchange mathjax can I use that here?)
 
on Phys.org
List comprehension takes some time to get used to but it's a very nice way to do a number of operations in one line and store the result as a new list.Let's simplify the comprehension slightly to piece together what is going on.

res = [i for i in list1]

This is the same as doing this: for i in list1: It just loops over list1 and i is the value of the current iteration. Ok now let's go back to the full example.

Code:
res = [i for i in list1 if i not in list2]

This is the same as doing this.
Code:
res = []
for i in list1:
    if i in list2:
        res.append(i)

The first version that uses list comprehension loops over list1 using i, then during each loop it checks "Is i in list2?" then it stores all of the results to another list which we call res.
 
But the original code said "if i NOT in list2" and your code says "i in list2".