Skip to content
Advertisement

Tag: list-comprehension

Finding prime numbers using list comprehention

I was trying to generate all prime numbers in range x to y. I tried simple example first: range(10,11) which means to check if 10 is a prime number: Here is my code: I know that the thing is missing the option to tell the expression that x%y != 0 should be checked for all y in range (2,x) and

Inline for loop

I’m trying to learn neat pythonic ways of doing things, and was wondering why my for loop cannot be refactored this way: I tried replacing the for loop with: But it doesn’t work. The for v in vm: loop evicts numbers from vm based on when they come next in q. Answer What you are using is called a list

Python LINQ like methods

As new to Python i really miss LINQ methods. I’ve found this and this questions, which helped me a lot to understand how Python enumerables and generators work. But sill, I want to use good old methods like Select, SelectMany, First, Last, Group, Distinct and so on. I understand, that all cases can be handled by generator and/or for expressions,

How to handle exceptions in a list comprehensions?

I have some a list comprehension in Python in which each iteration can throw an exception. For instance, if I have: I’ll get a ZeroDivisionError exception in the 3rd element. How can I handle this exception and continue execution of the list comprehension? The only way I can think of is to use a helper function: But this looks a

How do I remove duplicates from a list, while preserving order?

How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order. Is there a built-in or a Pythonic idiom? Answer Here you have some alternatives: http://www.peterbe.com/plog/uniqifiers-benchmark Fastest one: Why assign seen.add to seen_add instead of just calling seen.add? Python is a dynamic language, and resolving seen.add each iteration is more

Advertisement