Python - List Comprehension

Python - List Comprehension

List comprehension is a concise way to create lists in Python. It provides a more syntactically elegant and readable approach to generating lists compared to using loops.

The basic syntax of a list comprehension is:

[expression for item in iterable if condition] 
  • expression is the current item in the iteration, but it's also the outcome, which can be any arbitrary expression.
  • item is the variable that takes the value of the item inside the iterable.
  • iterable is a sequence, an iterator, or some other object that can return its elements one at a time.
  • condition is a filter that only accepts the items that evaluate as True.

Here are some examples to demonstrate the power and flexibility of list comprehensions:

  1. Generating a List of Numbers:

    nums = [x for x in range(10)] print(nums) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
  2. Squaring Each Element:

    squares = [x**2 for x in range(10)] print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 
  3. Using a Condition:

    even_squares = [x**2 for x in range(10) if x % 2 == 0] print(even_squares) # Output: [0, 4, 16, 36, 64] 
  4. Nested List Comprehensions:

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row] print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] 
  5. Combining Elements of Two Lists:

    list1 = ['a', 'b', 'c'] list2 = [1, 2, 3] combined = [(x, y) for x in list1 for y in list2] print(combined) # Output: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ...] 

List comprehensions are powerful, but they should be used judiciously. If the comprehension becomes too complex or hard to understand, it might be better to use a regular loop for clarity. Remember, readability counts in Python!


More Tags

serializable gpgpu export-to-csv sql-server-2014-express rar named-pipes telephony executemany angularjs-material cryptography

More Programming Guides

Other Guides

More Programming Examples