Python-Confused in list comprehension-:

  • MHB
  • Thread starter shivajikobardan
  • Start date
  • #1
shivajikobardan
559
35
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?)
 

Answers and Replies

  • #2
Jameson
Gold Member
MHB
4,538
13
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.
 
  • #3
HOI
923
2
But the original code said "if i NOT in list2" and your code says "i in list2".
 

Suggested for: Python-Confused in list comprehension-:

Replies
1
Views
178
Replies
10
Views
1K
Replies
2
Views
996
Replies
25
Views
2K
Replies
5
Views
889
Replies
9
Views
584
Replies
34
Views
1K
Replies
5
Views
516
Replies
8
Views
807
Top