10 examples of 'list comprehension' in Python

Every line of 'list comprehension' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
231def is_comprehension(x):
232 """Returns true if this is a comprehension type."""
233 return isinstance(x, (ObjectComprehension, SetComprehension, ArrayComprehension))
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

126@abstractmethod
127def visit_list_comprehension(self, o: 'mypy.nodes.ListComprehension') -> T:
128 pass
1042@utils.check_messages("using-constant-test", "missing-parentheses-for-call-in-test")
1043def visit_comprehension(self, node):
1044 if node.ifs:
1045 for if_test in node.ifs:
1046 self._check_using_constant_test(node, if_test)
19def test_filtering_lists_with_list_comprehensions(self):
20 feast = ['spam', 'sloths', 'orangutans', 'breakfast cereals',
21 'fruit bats']
22
23 comprehension = [delicacy for delicacy in feast if len(delicacy) > 6]
24
25 self.assertEqual(5, len(feast))
26 self.assertEqual(3, len(comprehension))
45def create_comprehension(for_node: ast.For) -> ast.comprehension:
46 return ast.comprehension(target=for_node.target, iter=for_node.iter, ifs=[])
500def visit_list_comprehension(self, o: 'mypy.nodes.ListComprehension') -> str:
501 return self.dump([o.generator], o)
32@property
33def iterable(self):
34 return self._args[1]
929@backtrackable
930@memoize
931def parse_comprehension_iter(self):
932 """
933 rule =
934 | comprehension_for
935 | comprehension_where
936 """
937 result = self.parse_comprehension_for()
938 if result is None:
939 result = self.parse_comprehension_where()
940
941 return result
2845def p_comp_for2(p):
2846 ''' comp_for : FOR exprlist IN or_test comp_iter '''
2847 target = p[2]
2848 set_context(target, Store, p)
2849 gens = []
2850 gens.append(ast.comprehension(target=target, iter=p[4], ifs=[]))
2851 for item in p[5]:
2852 if isinstance(item, ast.comprehension):
2853 gens.append(item)
2854 else:
2855 gens[-1].ifs.append(item)
2856 p[0] = gens
40def wrong_comprehension2():
41 return [
42 target # noqa: WPS224
43 for assignment in range(hex_number)
44 for target in range(assignment)
45 for _ in range(10)
46 if isinstance(target, int)
47 ]

Related snippets