Enhancing Performance with List Comprehensions in Python

Learn how to use list comprehensions in Python to efficiently create lists and improve the performance of your data processing tasks.

0 likes
15 views

Rule Content

{
  "title": "Enhancing Performance with List Comprehensions in Python",
  "description": "Learn how to use list comprehensions in Python to efficiently create lists and improve the performance of your data processing tasks.",
  "category": "Python Cursor Rules",
  "rules": [
    {
      "pattern": "for\\s+\\w+\\s+in\\s+\\w+:\\s+\\n\\s+\\w+\\.append\\(.*\\)",
      "message": "Consider using a list comprehension to simplify this loop and improve performance.",
      "replacement": "[\\2 for \\1 in \\3]",
      "example": {
        "bad": "squared_numbers = []\nfor num in numbers:\n    squared_numbers.append(num ** 2)",
        "good": "squared_numbers = [num ** 2 for num in numbers]"
      }
    },
    {
      "pattern": "\\[.*for\\s+\\w+\\s+in\\s+\\w+\\s+if\\s+.*\\]",
      "message": "Ensure that the list comprehension is not overly complex; consider breaking it into multiple comprehensions or using traditional loops for better readability.",
      "example": {
        "bad": "result = [x + y for x in range(10) if x % 2 == 0 for y in numbers if y % 2 != 0]",
        "good": "evens = [x for x in range(10) if x % 2 == 0]\nodds = [y for y in numbers if y % 2 != 0]\nresult = [x + y for x in evens for y in odds]"
      }
    },
    {
      "pattern": "\\[.*for\\s+\\w+\\s+in\\s+\\w+\\s+if\\s+.*else\\s+.*\\]",
      "message": "Avoid using 'if-else' within list comprehensions for complex conditions; use a regular loop for better clarity.",
      "example": {
        "bad": "labels = ['Yes' if prob > 0.5 else 'No' for prob in probabilities]",
        "good": "labels = []\nfor prob in probabilities:\n    if prob > 0.5:\n        labels.append('Yes')\n    else:\n        labels.append('No')"
      }
    },
    {
      "pattern": "\\[.*for\\s+\\w+\\s+in\\s+\\w+\\s+for\\s+\\w+\\s+in\\s+\\w+\\]",
      "message": "Limit nested list comprehensions to one level to maintain readability; consider using nested loops for deeper nesting.",
      "example": {
        "bad": "pairs = [(x, y) for x in range(3) for y in range(3) for z in range(3)]",
        "good": "pairs = []\nfor x in range(3):\n    for y in range(3):\n        for z in range(3):\n            pairs.append((x, y, z))"
      }
    },
    {
      "pattern": "\\[.*for\\s+\\w+\\s+in\\s+\\w+\\s+if\\s+.*\\]",
      "message": "Use descriptive variable names in list comprehensions to enhance code readability.",
      "example": {
        "bad": "squares = [x**2 for x in range(10) if x % 2 == 0]",
        "good": "even_squares = [number**2 for number in range(10) if number % 2 == 0]"
      }
    }
  ]
}