Answers for "what is list comprehension in python"

1

python list comprehension elif

>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']
Posted by: Guest on November-16-2020
22

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
2

python list comprehension

nums = [3578, 6859, 35689, 268]
half_of_nums = [x/2 for x in nums]
Posted by: Guest on January-04-2021
1

list comprehension python

# without using List comprehension
numbers = [1,2,3]
new_list = []

for num in numbers:
    new_list.append(num * 2)
print(new_list)

# List comprehension
new_list_compre = [num * 2 for num in numbers]
print(new_list_compre)

# List comprehension using range
double_list = [i*2 for i in range(1,5)]
print(double_list)

# conditional List Comprehensions
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
# getting names less than 5 letters
short_names = [name for name in names if len(name) < 5]
print(short_names)
Posted by: Guest on January-30-2021
3

python list comprehension

lst=[1,2,3,4,5]
lst2=[item for item in lst if <condition>]
# generates a list based on another list and an if statement. the code above is a replacement for:
lst=[1,2,3,4,5]
lst2=[]
for item in lst:
  if <condition>:
    lst2.append(item)
Posted by: Guest on January-04-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

Code answers related to "what is list comprehension in python"

Python Answers by Framework

Browse Popular Code Answers by Language