Skip to content

Instantly share code, notes, and snippets.

@KeyurRamoliya
Created September 14, 2023 16:30
Show Gist options
  • Save KeyurRamoliya/393c09b3dc5d791f50cbb59185310d1a to your computer and use it in GitHub Desktop.
Save KeyurRamoliya/393c09b3dc5d791f50cbb59185310d1a to your computer and use it in GitHub Desktop.
List Comprehensions In Python

List Comprehensions In Python

Python's list comprehensions are a powerful and concise way to create lists. They can make your code more readable and reduce the need for explicit loops. Instead of writing a loop to generate a list, you can use list comprehension in a single line.

Using list comprehensions reduces the amount of code you need to write and makes your code more Pythonic and easier to understand.

Consider the below example demonstrating the use of list comprehensions to create a list of squares for all numbers from 1 to 10.

# Without list comprehension
squares = []
for num in range(1, 11):
    squares.append(num * num)

# With list comprehension
squares = [num * num for num in range(1, 11)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment