4

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Austin
  • 114
  • 7

2 Answers2

3

The only problem here is that newNums:

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

is a generator, and as far as I know, you cannot call len(..) on a genrator and the printing does not show it elements, but only that it is an enumerator.

You can use list comprehension to construct a list. All you have to do is replace the round brackets ((..)) with square ones ([..]):

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

Finally a small note:

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.

You are correct, except that your syntax seems to suggest that it emits lists, it emits tuples, so (0,1), (1,8),... but this is in this context a minor detail.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
3

the small problem with your code is that

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

is a generator (e.g. len will not work on it). what you want is a list (comprehension):

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

with this the rest of your code works as you expect it.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111