Python-Confused in list comprehension-:

terabaaphoonmein

Joined Jul 19, 2020
101
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???)

Papabravo

Joined Feb 24, 2006
18,400
If you don't have a Python 3 language reference, I would start by rounding one up.
If you are not familiar with any Python variant I would go back and find a basic tutorial.

What it is doing is using two existing lists to create a new list. The values in this new list called res, by taking the elements in list1 and checking to see if they are in list2. It should have one entry for each "i" in list 1. There are no specific indexes or loops being used. Python is smart enough to work all that stuff out for you. I think I remember these being called associative arrays, but I could be confusing that term with something else.

Ya’akov

Joined Jan 27, 2019
5,647
If you don't have a Python 3 language reference, I would start by rounding one up.
If you are not familiar with any Python variant I would go back and find a basic tutorial.

What it is doing is using two existing lists to create a new list. The values in this new list called res, by taking the elements in list1 and checking to see if they are in list2. It should have one entry for each "i" in list 1. There are no specific indexes or loops being used. Python is smart enough to work all that stuff out for you. I think I remember these being called associative arrays, but I could be confusing that term with something else.
Associative Arrays ("hashes" in perl) are arrays with names (called "keys") instead of numbers as indices. They are also called "maps" and "dictionaries" in other languages.