List Comprehension

Run Settings
LanguagePython
Language Version
Run Command
# Type - 1 (SIMPLE LIST COMPREHENSION) alpha_list = [i for i in "Hello World"] print(alpha_list) # Type - 2 (LIST COMPREHENSION WITH OPERATION) square_numbers = [i**2 for i in range(11)] print(square_numbers) # Type - 3 (LIST COMPREHENSION WITH IF condition) even_list = [ i for i in range(11) if i % 2 == 0] print(even_list) str = "a12bcd3efg456" alpha_list = [i for i in str if i.isalpha()] print(alpha_list) alpha_str = "".join([i for i in str if i.isalpha()]) print(alpha_str) # Type - 4 (LIST COMPREHENSION WITH IF-ELSE condition) str = "a12bcd3efg456" alpha_num_list = [i.upper() if i.isalpha() else int(i)**2 for i in str] print(alpha_num_list) # Type - 5 (LIST COMPREHENSION WITH NESTED IF conditions) lst = [-2, 10, 5, 3, -1, 0, -15, 6, -30, 12] positive_even_list = [ i for i in lst if i > 0 if i % 2 == 0 ] print(positive_even_list) # Type - 6 (LIST COMPREHENSION WITH NESTED loops) nested_loop_list = [ i for i in range(5) for j in range(i) ] print(nested_loop_list)
Editor Settings
Theme
Key bindings
Full width
Lines