list comprehension Flashcards
fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = []
for x in fruits:
if “a” in x:
newlist.append(x)
print(newlist)
fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [x for x in fruits if “a” in x]
print(newlist)
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
int(input(‘k: ‘)
print with list comprehension
n = 1
for i in range(int(input(‘k: ‘))):
print(list(i for i in range(0, n)))
n += 1
from a ls = [0,1,2,3,4,5,6,7,8,9], print the ones which are greater than 4
ls = [0,1,2,3,4,5,6,7,8,9]
ls2 = [i for i in ls if i > 4]
print(ls2)
Create dict from 1 list by list compr:
ls1 = [‘alma’, ‘körte’, ‘szilva’]
ls2 = [23, 10, 45]
d = {ls1[i]:ls2[i] for i in range(len(ls1))}
print(d)
from random import *
ls = []
for i in range(20):
k = random.randint(0,100)
ls.append(k)
print(ls)
import random
ls = [random.randint(0,100) for i in range(20)]
print(ls)
[2, 2, 2, 2, 2]
[2, 2, 2, 2, 2]
[2, 2, 2, 2, 2]
[2, 2, 2, 2, 2]
[2, 2, 2, 2, 2]
oszlop = 5
sor = 5
matrix = [[2 for i in range(oszlop)] for j in range(sor)]
for i in matrix:
print(i)
[1, 2, 2, 2, 2]
[2, 1, 2, 2, 2]
[2, 2, 1, 2, 2]
[2, 2, 2, 1, 2]
[2, 2, 2, 2, 1]
oszlop = 5
sor = 5
matrix = [[2 for i in range(oszlop)] for j in range(sor)]
for i in matrix:
print(i)
counter = 0
for i in matrix:
i[counter] = 1
counter += 1
print(‘\n’)
for i in matrix:
print(i)
[1, 1, 1, 1, 5]
[1, 1, 1, 5, 1]
[1, 1, 5, 1, 1]
[1, 5, 1, 1, 1]
[5, 1, 1, 1, 1]
oszlop = 5
sor = 5
matrix = [[1 for i in range(oszlop)] for j in range(sor)]
for i in matrix:
print(i)
counter = sor -1
for i in matrix:
i[counter] = 5
counter -= 1
print(‘\n’)
for i in matrix:
print(i)