Answers for "list comprehensions"

21

list comprehension python

# All of the possibilies that can be done with the List Comprehension

vec = [-4, -2, 0, 2, 4]
# create a new list with the values doubled

doubled = [x*2 for x in vec]
# [-8, -4, 0, 4, 8]

# filter the list to exclude negative numbers
greater_thatn_0 = [x for x in vec if x >= 0]
# output [0, 2, 4]

# apply a function to all the elements
positive = [abs(x) for x in vec]
#  output [4, 2, 0, 2, 4]

# call a method on each element
freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
fruits_nospaces = [weapon.strip() for weapon in freshfruit]
# output ['banana', 'loganberry', 'passion fruit']

# create a list of 2-tuples like (number, square)
squares = [(x, x**2) for x in range(6)]
# output [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

# the tuple must be parenthesized, otherwise an error is raised
# error = [x, x**2 for x in range(6)]
  #   error = [x, x**2 for x in range(6)]
                     ^
# SyntaxError: invalid syntax

# flatten a list using a listcomp with two 'for'
vec = [[1,2,3], [4,5,6], [7,8,9]]
unpacking_tuple = [num for elem in vec for num in elem]
# output [1, 2, 3, 4, 5, 6, 7, 8, 9]
Posted by: Guest on December-31-2020
31

python list comprehension

nums = [4, -7, 9, 1, -1, 8, -6]
half_of_nums = [x/2 for x in nums] #[2, -3.5, 4.5, 0.5, -0.5, 4, -3]

#optionally you can add an if statement like this
half_of_positive_nums = [x/2 for x in nums if x>=0] #[2, 4.5, 0.5, 4]
Posted by: Guest on May-20-2020
9

python list comprehension

#example: removing common elements found in `a` from `b`.
a = [1,2,3,4,5]
b = [5,6,7,8,9]
# desired output: [1,2,3,4]

# gets each item found in `a` AND not in `b`
print([i for i in a if i not in b])
Posted by: Guest on October-22-2020
0

List Comprehensions

numbers = [1, 2, 3, 4, 5, 6]
squares = [i*i for i in numbers]

print(squares)
Posted by: Guest on March-22-2021
0

list comprehensions

S = [x**2 for x in range(10)]
V = [2**i for i in range(13)]
Posted by: Guest on April-22-2021
0

list comprehensions

[output_expression for element in list if condition]Code language: Python (python)
Posted by: Guest on October-04-2021

Browse Popular Code Answers by Language