python find difference between two lists [duplicate] - python

This question already has answers here:
Get difference between two lists with Unique Entries
(32 answers)
Closed 6 years ago.
I am new to programming but I keep learning, and recently I hit the wall so I'm asking for help.
Sorry if this was discussed before, but I can't find answer to my problem.
I have two lists. And I need to compare them, and in the result to get the objects that DON'T match. For example:
a = [1,2,3,4,5,6]
b = [1,2,3,4,5,6,7,8,9]
result = [7,8,9].
And I only seem to find code and examples that return matches. Which I don't need.
Lists are in file notepad file.txt for you folks to keep in mind if you this helps you to help me. :)

You can convert the lists to sets and run the usual set operations such as difference or symmetric difference. For example, set(b) - set(a) evaluates to set([7, 8, 9]).

If the second set is not always a subset of the first then the difference operator '-' may not always return what you expect.
E.g.
[1,2,3,4,5] - [3,4,5,6,7] = [1,2]
If you want a set of items in either list but not both lists use the symmetric difference operator '^'.
[1,2,3,4,5] ^ [3,4,5,6,7] = [1,2,6,7]
The symmetric difference operator, assuming it does what you want, also has the advantage of being commutative. This means you don't need to determine in which order to compare the sets like you do with the difference operator.
http://docs.python.org/2/library/stdtypes.html#set

Related

How to assign two function return values to two variables and use them in the same line? [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
How do I iterate through two lists in parallel?
(8 answers)
Closed 11 months ago.
Right, so this might be a rather confusing question. But in my Computer science class, we were given this optional challenge to calculate the distances a catapult has achieved after a user inputs a set of angles and speeds. But the challenge is that we have to split the problem into multiple smaller functions but each function is only allowed to have one statement per function.
I think I have a way to do it but I'm having trouble with one part.
[x = get_angles(), y = get_speeds(): 2*x[i]*y[i]/GRAVITY for i in range(len(x))]
This is part of my code for creating a list of the distances travelled. Now, this is effectively pseudo-code cause I have no clue how to make it work. Does python have anything that allows something like this to happen?
Any help would be great. Sorry for being so long-winded but thanks anyway :)
Trying to change the line of code you provided into something that works, I got this:
(lambda x, y: [2*x[i]*y[i]/GRAVITY for i in range(len(x))])(get_angles(), get_speeds())
This trick uses a lambda function to "store" the x, y values and use them in the same line.
I'm not sure this does exactly what you want, but this lambda function trick still applies.

How the operator (is) works with tuples and lists [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 4 years ago.
Why when I compare two equal tuples through the operator (is) I get a different result than when I compare two equal lists? (one is True an the other is False)
Nothing really... i am starting with python and i do not want to leave my doubts :)
a=(1,2,3)
b=(1,2,3)
c=[1,2,3]
d=[1,2,3]
print(a is b) #True
print(c is d) #false
I expected that both were False :(
Python may optimize small read-only objects (strings, numbers, tuples) by "interning" them (keeping a list of common small objects), or noticing they are the same at compile-time and not making a second copy.
Since these objects can not be changed, this is a safe optimization, and can result in is returning True for two objects that would otherwise be separate.
The actual specifics are version specific and can change from release to release. They are certainly equals (==) , but may or may not be the same (is).
Lists can be modified (they are mutable), therefore, under the current language rules, they have to be viewed as different objects. They have separate identify and are not is the same. Otherwise changing c would change d.

how do you turn a matrix to a list in python? [duplicate]

This question already has answers here:
Double Iteration in List Comprehension [duplicate]
(11 answers)
Closed 4 years ago.
nums_lst = [x for y in matrix for x in y]
Could anyone please help me understand what does the line x for y in matrix for x in y mean? matrix is of type list[[]]
What is x and what is y in the matrix?
Thank you for your help.
This is called list comprehension. There’s plenty of tutorials but it’s basically flattening 3 or 4 lines of code into one. Put anyway instead of creating a list within a loop you use this special syntax.
Here’s a good description of the technique enter link description here
You can also use dictionary comprehensions.
Once you get used to the syntax then comprehensions do result in nice clean code.
I suggest the following learning path. Try figure out a basic list comprehension first, for example take a list of integers and turn it into a list of squared integers. Then move onto the two dimensional element.

How to make a list of multiples and use a for loop to print in Python3 [duplicate]

This question already has answers here:
How do you check whether a number is divisible by another number?
(9 answers)
Closed 6 years ago.
The question in my book I am working through (I am new to programming) is:
Threes: Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
I have tried a few different things to do this, but in my book Python Crash Course, it doesn't explain the syntax or show me examples on how to do multiples. Only exponents. I have reread the chapter several times over and still am not able to find the tutorial on how to do this. And also, being that I am new to programming, I don't exactly know the keywords or phrases I should be searching for.
It would be of great help to me (I've been confused by this for over an hour) if someone could explain this to me and give me an example.
It's easy, you can use the range function to iterate over a sequence of numbers and then create the list by examining the result of value % 3 (modulus 3). If it is zero, you got a multiple, if not, you don't:
# Create an empty list
l = []
# 31 because the end of the range is exclusive
for i in range(3, 31):
# if equal to zero it is a multiple of 3
if i % 3 == 0:
# add it to the list
l.append(i)
This can be mushed into a single line called a comprehension:
l = [i for i in range(3, 31) if i % 3 == 0]
As for printing, you can tackle it, you use a similar for loop through the list l created and then use the print function!
Since you're new to the language, go over to the Python homepage and read the official tutorial on the language, it is nicely written and will help you much more than any answer can.

Conditional operator in python dictonaries and set [duplicate]

This question already has answers here:
Comparing two sets in python
(3 answers)
Closed 4 months ago.
I am preparing for an exam of python certification and found these question which are still unsolved by me. Please Help.
http://www.vskills.in/certification/practice-test/Information-Technology/Python/Python-Test-Set/Python-Developer-Test-Set-5
a = {2,2,3,4}
b = {1,2,3}
>>> b<a
False
>>> a<b
False
upto python 2.7 this also works Now I think they have fixed.
{1:2,2:3,3:4}<{2:5,3:6,4:7,5:8}
True
[1,2,3]==(1,2,3)
False
My question is their any logic behind these type of conditional operator on dictonaries or not.
Python 2 tries to provide a sort order for almost everything; dictionaries are no exception.
Dictionaries are arbitrarily but consistently ordered when compared to one another to ensure that you can sort a heterogenous list that contains them. You should not derive any meaning from their comparisons, really.
Python 3 abandoned the notion that all objects should be ordered relative to one another and using comparison operators other than equality and identity on dictionaries raises a TypeError instead.
Sets overload comparison operators to signal subsets. If set_a is a subset of set_b then set_a < set_b is true. See the set types documentation.
To translate all this to your specific examples:
Your two sets are not subsets of one another; one has the value 4 and the other the value 1 which are not shared. Testing for a subset fails in both directions.
{1:2,2:3,3:4} < {2:5,3:6,4:7,5:8} is True because the first dictionary has fewer keys. The choice is arbitrary, there isn't any specific meaning to this other than that this means the two dictionaries will always be ordered consistently within one Python version.
Your last sample compares two different types. A tuple is never equal to a list, even if they have the same contents.

Categories