Reputation: 39
I'm fairly new to programming.
Basically in a list of floats, I want my program to print every one that starts with either '1' or '-1'. This is what I have so far.
def oneminus(L):
for i in range(len(L)):
if L[i][0]=='1':
print(L[i])
elif L[i][0]=='-' and L[i][1]=='1':
print(L[i])
When I run the program however I get the error "TypeError: 'float' object is not subscriptable" So I'm assuming the issue is due to the fact the list contains floats.
Upvotes: 0
Views: 854
Reputation: 39451
The problem is that you're treating the elements as strings, not floats. Unlike PHP and Javascript, Python doesn't have implicit type coercion. If you want to get the string representation, you have to convert it explicitly using str
or repr
.
What you want is something like
def oneminus(L):
for x in L:
if str(x).startswith('1') or str(x).startswith('-1'):
print(x)
You could make it shorter by taking advantage of str.strip
.
def oneminus(L):
for x in L:
if str(x).strip('-').startswith('1'):
print(x)
Also note that you can iterate over a list directly.
Upvotes: 1