Cast to int not working in Python - python

I'm trying to store a time value in an array, but it gives me an error every time, even when I try to cast the float into an int. Here is the portion of my code:
EndTimes = [0,0,0,0]
...
EndTimes[TakenSlots] = int(time.time() + n)
But it just gives this error:
[error] TypeError ( list indices must be integers )
[error] --- Traceback --- error source first
line: module ( function ) statement
44: main ( craftTime ) EndTimes[TakenSlots] = tempInt
I tried this code just to see what it thought the value was:
tempInt = int(time.time() + n)
print tempInt
EndTimes[TakenSlots] = tempInt
And it just outputted 1412046180 (no decimal places, which seems like it should be an int)
Does anyone know what's happening? Is it a problem with the int() or the type of array I'm using? Thanks in advance!

This occurs because the list index ( list[index] = value ) must be an integer. It is probable that TakenSlots is not an int.
>>> l = [1,2,3]
>>> l[1.3] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float

Related

TypeError: list indices must be integers, not float (Python2)

import math
a=[100,4,5,10,3,1]
def swap(a,b):
temp=a
a=b
b=temp
for i in range(len(a),int(len(a)/2),-1):
l=i
print l
print int(math.ceil(int((l)/2.0)))
print a[int(math.ceil(int((l)/2.0)))]
print math.ceil(a[int((l)/2.0)])
print a[l-1]
while(l>1 and a[l-1] < a[int(math.ceil(int((l)/2.0)))]):
swap(a[l-1],a[int(math.ceil(int((l)/2.0)))])
print l
l= math.ceil(int((l))/2.0)
print a
Output:
6
3
10
10.0
1
6
Traceback (most recent call last):
File "heap.py", line 15, in <module>
while(l>1 and a[l-1] < a[int(math.ceil(int((l)/2.0)))]):
TypeError: list indices must be integers, not float
I have checked many questions on stackoverflow with same query, I
tried using the // as well but the error is persistent. I am using the
int value as I printed and tested. Can anyone redirect me to a
question with similar issue( if this duplicate) or help me with this
error?

getting space separated input in python

I am trying to get space separated inputs. while the first method works completely fine, the second method throws an error saying:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
what is wrong with the second method?
Method 1:
x = [int(j) for j in input().split()]
Method 2:
x = [j for j in int(input().split())]
Because you are using split() to a string which will return a list, then you are passing this list to int() that's why you are getting error. for changing datatype of list you need to use map() as below or first approach of your's.
Try Below code
x = [j for j in map(int,input().split())]

Python list types

This is quite a weird/silly question so if anyone as a better title name, please request an edit.
I've created a function that returns the product of numbers in a list.
When testing this function, I tried lists that that included intergers and reals(floats), such as items = [1,2.0,3,4.0]
Function:
items = [1.0, 2, 3.0, 10, "a"]
def mult1(items):
total = 1
for i in items:
total = total * i
return total
print mult1(items)
This function above works with items being [1.0, 2, 3.0, 10] and the output of that particular list being 60.0.
I've studied Standard ML where you can only generally have a list of a particular type (I'm sure there's code out there that somehow makes my statement irrelevant), so intrigued to find out what would happen if I entered a string as a list item, I did, and got an error (I expected to get an error because you can't multiply a string with a number).
However, the error I received has confused me:
TypeError: can't multiply sequence by non-int of type 'float'
This error has confused me. I understand that a string cannot be multiplied, but does this also suggest that all of the items in the list are considered a float despite some looking like integers?
I thought that the error should suggest it cannot compute a type that is not a float or not an integer, but to me (probably wrong) it seems like it's suggesting that it can't multiply the list by a a type that is not an integer that is also not of type float?
To me this sounds like each element has two types, integer and float.
You're getting this error because you are (perhaps unintentionally) multiplying a sequence (list, str, tuple) by a float.
>>> a = [1, 2]
>>> a * 2
[1, 2, 1, 2]
>>> a * 2.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
>>>
This error occurs because you can actually multiply some non-number types by ints, but not by floats. So if your product function looks something like:
def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
return prod
and your list looks like this : l = ['this string',3,2.0]
then your iterations will show the following:
>>> def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
print(prod)
return prod
>>> l = ['this string',3,2.0]
>>> product(l)
this stringthis stringthis string
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
product(l)
File "<pyshell#67>", line 4, in product
prod *= x
TypeError: can't multiply sequence by non-int of type 'float'
note that the first iteration is allowed because str*int is a valid expression (so is list*int and tup*int etc) and so prod is still valid but is a STRING, not an int or float. then when you DO try to do a str*float expression, the TypeError will occur.
You can multiply a string but only by an int, you see the error as you are trying to multiply a string by a float:
In [7]: "foo" * 2
Out[7]: 'foofoo'
In [8]: "foo" * 2.0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-3128e6ce951c> in <module>()
----> 1 "foo" * 2.
TypeError: can't multiply sequence by non-int of type 'float'
In your particular case you are trying to multiply a from your list by a float:
[1.0, 2, 3.0, 10, "a"]
^
error
Total starts out an int but when you multiply an int by a float you get a float so total = total * 1.0 -> 1.0:
In [9]: 1 * 1.0
Out[9]: 1.0

Reading in integer from stdin in Python

I have the following piece of code where I take in an integer n from stdin, convert it to binary, reverse the binary string, then convert back to integer and output it.
import sys
def reversebinary():
n = str(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()
However, I'm getting this error:
Traceback (most recent call last):
File "reversebinary.py", line 18, in <module>
reversebinary()
File "reversebinary.py", line 14, in reversebinary
bin_n = bin(n)[2:]
TypeError: 'str' object cannot be interpreted as an index
I'm unsure what the problem is.
You are passing a string to the bin() function:
>>> bin('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an index
Give it a integer instead:
>>> bin(10)
'0b1010'
by turning the raw_input() result to int():
n = int(raw_input())
Tip: you can easily reverse a string by giving it a negative slice stride:
>>> 'forward'[::-1]
'drawrof'
so you can simplify your function to:
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = bin_n[::-1]
return int(revbin, 2)
or even:
def reversebinary():
n = int(raw_input())
return int(bin(n)[:1:-1], 2)
You want to convert the input to an integer not a string - it's already a string. So this line:
n = str(raw_input())
should be something like this:
n = int(raw_input())
It is raw input, i.e. a string but you need an int:
bin_n = bin(int(n))
bin takes integer as parameter and you are putting string there, you must convert to integer:
import sys
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()

What does "Type Error: Can't convert 'int' to str implicitly" mean?

def display_positive_indices(strlen):
print()
print(' ', end='')
for i in range(strlen + 1):
print(i, end='')
if i != strlen:
print(' ' * (4 - len(str(i))), end='')
print()
Hi, I'm new to programming. This is my code. The error first points to the main function. Then it points to this function in the main then it points to:
for i in range(strlen + 1) and it says Type Error: Can't convert 'int' object to str implicitly. Why does it say this? What can I do to fix this error?
Your function works fine if you call it with an integer, such as:
In [499]: display_positive_indices(3)
0 1 2 3
But when you call it with a string, you get this error, and the interpreter tells you more information:
In [500]: display_positive_indices('3')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-500-dd39f751056c> in <module>()
----> 1 display_positive_indices('3')
<ipython-input-495-ac7e32dd0c50> in display_positive_indices(strlen)
2 print()
3 print(' ', end='')
----> 4 for i in range(strlen + 1):
5 print(i, end='')
6 if i != strlen:
TypeError: Can't convert 'int' object to str implicitly
The problem is that strlen + 1. You're trying to add a str to an int. You get the exact same error with just this:
In [501]: strlen = '3'
In [502]: strlen + 1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-502-5a3ed0dba868> in <module>()
----> 1 strlen + 1
TypeError: Can't convert 'int' object to str implicitly
In Python 3, trying to add something to a str starts off by trying to implicitly convert that other thing to a str, and, as the error says, you can't do that with an int.
Meanwhile, for future reference, here's how to debug an error like this:
To start off with, you know which line in your function has the error. So, keep removing stuff until the error goes away. First:
def display_positive_indices(strlen):
for i in range(strlen + 1):
pass
Same error. So:
def display_positive_indices(strlen):
range(strlen + 1)
And again:
def display_positive_indices(strlen):
strlen + 1
And:
def display_positive_indices(strlen):
strlen
OK, that last one succeeded, so the problem was in strlen + 1. Everything else is irrelevant. So, you've narrowed down what you have to figure out, ask about, and/or understand.
Finally, if you want us to figure out what's wrong with the main function, and why it's passing a str rather than the int you expected, you'll have to show us that function. (Of the top of my head, my first guess is that you're using input to get a length from the user, and not converting it, possibly because you read the Python 2 docs on input instead of the Python 3 docs. But I'd give that guess a 20% chance of being right at best.)
Since you require an integer you can coerce it to the type you would like, and if it cannot be converted you will get a TypeError or ValueError:
...
strlen = int(strlen)
for i in range(strlen + 1):
...

Categories