How can I get the length of a list in list comprehension

Viewed 121

I tried to do the following:

quizes = Quiz.query.all()
math_quizzes = [quiz for quiz in quizes if quiz.category == "Math" and len(math_quizzes) < 10]

But len(math_quizzes) < 10 doesn't work, So how can I do it?

2 Answers

Can you try to limit it on Query side?

math_quizzes = Quiz.query.filter(Quiz.category == "math").limit(10).all()

Your and operation will not work, as you are trying it on same list math_quizzes, Try sliceing to print the number of records.

quizes = Quiz.query.all()
print([quiz for quiz in quizes if quiz.category == "Math"][:11])
Related