I am generating a list of 12 random numbers:
nums = []
for num in range(12):
nums.append(random.randint(1,20))
I would then like to search 'nums' for a specific number, say '12' and use an if statement to print if it showed up and where in the list. Something like this:
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 the list where I have the locations listed of where '12' is inside of the 'nums' list.
I tried a few different things with a for loop that didn't get me anywhere and then I found something on here that looked like this:
newNums = (i for i,x in enumerate(nums) if x == 12)
However, when I try to print that it does not do what I am looking for. I must have misunderstood its purpose. My understanding of the enumerate
function is that it provides the index of where the value is located, followed by the value; ex: [0,1]
, [1,8]
, [2,6]
etc. I am reading that code to mean: give me the i value in a pair of [i,x]
inside the list (nums
) if the x == 12
.
I am new to python within the past couple of weeks, so any advice is welcome. I may just be misunderstanding how the code works.
Thank you for your time.