Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Python-Confused in list comprehension-:

shivajikobardan

Legendary Coder
Python-Confused in list comprehension-:

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???)
 
Lets pull this apart and go from there 🙂 So we have our two lists, List 1 and List 2. If we was to do

Python:
for i in list1:
    print(i)

our output would be :-
1
3
4
6
7

So what your res is doing is this :-
Python:
complete = []
for i in list1:
    if i not in list2:
        complete.append(i)

i have had to add a new list called complete to simplify this but with the other way you are simply add the variable to i. What you are doing in a nut shell is loading the first record in list1 (for i in list1🙂 so 1. we then check to see if 1 is in list 2 by doing (if i not in list2🙂 if its not in list 2 then we append this to a new list called complete (complete.append(i)) we then print this at the end
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom