How can I search a list in python and print where in my list are my criteria?

I generate a list of 12 random numbers:

nums = []    
for num in range(12):
    nums.append(random.randint(1,20))

Then I would like to search for "nums" for a specific number, for example, "12" and use the if statement to print if it appeared and where in the list. Something like that:

if len(newNums) == 0:
    print('No, 12 is not a part of this integer list')
elif len(newNums) < 2:
    print('Yes, 12 is in the list at index', newNums[0])
else:
    print('Yes, 12 is in the list at indices', newNums)

In this case, β€œnewNums” is a list showing locations where β€œ12” are inside the β€œnums” list.

I tried a few different things with a for loop that didn't deliver me at all, and then I found something like this here:

newNums = (i for i,x in enumerate(nums) if x == 12)    

, , , . , . enumerate , , , ; ex: [0,1], [1,8], [2,6] .. : [i,x] (nums), x == 12.

python , . , , .

.

+4
2

, newNums:

newNums = (i for i,x in enumerate(nums) if x == 12) # a generator

, , , len(..) genrator, , , .

, . , , ((..)) ([..]):

newNums = [i for i,x in enumerate(nums) if x == 12] # a list
#         ^                                       ^

, :

enumerate , , , ; ex: [0,1], [1,8], [2,6] ..

, , , -, , , , (0,1), (1,8),... .

+3

,

newNums = (i for i,x in enumerate(nums) if x == 12)  

(, len ). ():

newNums = [i for i,x in enumerate(nums) if x == 12]

, .

+3

Source: https://habr.com/ru/post/1667446/


All Articles