How to get the number of times a number N appears in a nested list with Python

2 Answers

0 votes
import itertools, collections

nestedlist = [[1, 2, 3], [1, 5], [6, 1, 8, 9, 10], [1, 9, 10, 10], [1]]
N = 1

countN = collections.Counter(itertools.chain(*nestedlist))

print(countN[N])


'''
run:

5

'''

 



answered Feb 9, 2025 by avibootz
0 votes
nestedlist = [[1, 2, 3], [1, 5], [6, 1, 8, 9, 10], [1, 9, 10, 10], [1]]
N = 1

countN = sum(x.count(N) for x in nestedlist)

print(countN)


'''
run:

5

'''

 



answered Feb 9, 2025 by avibootz
...