-2

How to add numbers that begin with 1 to a list?

def digit1x(lx):
list = []

for num in lx:
    temp = str(num)
    if temp[0]== '1':
        list.append(int(temp))
return list

print(digit1x(lx))

updated code, and It works, thank you for your help!

3 Answers3

0

you cannot do num[0] if num is an int, for example you can write str(num)[0] == '1'. Don't forget to deal with special cases if any.

machine424
  • 155
  • 2
  • 9
0

You're thinking of numbers as starting with 1 in their base 10 representation? In that case, you should coerce to a string first before checking the digit:

>>> num = 12345
>>> str(num)
'12345'
>>> str(num)[0]
'1'
David Cain
  • 16,484
  • 14
  • 65
  • 75
0

The error is occuring because you cannot get the [0] index value of an integer. It is only posible to get an index value of an array or string. Create a variable ('temp'↓) that is the string variable of the [0] index of that integer and then use that in the conditional statement:

This works:

def digit1x(lx):
list = []

for num in lx:
    temp = str(lx[num])
    if temp[0] == '1':
        list.append(temp)
        return list

print(digit1x(lx))

The value of temp is the string value of the current item.

'temp[0]' is the first character in temp, and therefore the first character in the current item.

Therefore, if temp[0] equals '1' then the first number in the current item is 1.