list comprehension Flashcards

1
Q

fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = []

for x in fruits:
if “a” in x:
newlist.append(x)

print(newlist)

A

fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]

newlist = [x for x in fruits if “a” in x]

print(newlist)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

[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

A

n = 1

for i in range(int(input(‘k: ‘))):
print(list(i for i in range(0, n)))
n += 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

from a ls = [0,1,2,3,4,5,6,7,8,9], print the ones which are greater than 4

A

ls = [0,1,2,3,4,5,6,7,8,9]

ls2 = [i for i in ls if i > 4]

print(ls2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Create dict from 1 list by list compr:

ls1 = [‘alma’, ‘körte’, ‘szilva’]
ls2 = [23, 10, 45]

A

d = {ls1[i]:ls2[i] for i in range(len(ls1))}
print(d)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

from random import *

ls = []

for i in range(20):
k = random.randint(0,100)
ls.append(k)
print(ls)

A

import random

ls = [random.randint(0,100) for i in range(20)]

print(ls)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

[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

A

matrix = [[2 for i in range(oszlop)] for j in range(sor)]

for i in matrix:
print(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

[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

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

[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

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly