-1

We are working on a project where we are translating javaScript code into python. Everything is going pretty smoothly, except for this one line of code that has given us errors on multiple translations:

"primes" is an empty array BTW.

JavaScript:

 var primes = [];

 if(primes[primes.length - 1] > 3){...}

Python:

 primes = []

 if primes[len(primes) - 1] > 3:
      ......

This code works in javascript, however in Python we get an error. It seems as though we are trying to access an index of the list that doesn't exist.

This is the error:

TypeError: object of type 'int' has no len()

Does anyone have a workaround?

Nicholas Roberts
  • 222
  • 4
  • 13
  • 2
    Please show the line where you declare `primes`. – nnnnnn Jun 24 '16 at 20:28
  • 3
    `primes` is clearly *not* an empty array, it's `int`. Please create [mcve]. – GingerPlusPlus Jun 24 '16 at 20:31
  • In both instances we are declaring an array, how are we supposed to declare it if we're declaring ints? – Nicholas Roberts Jun 24 '16 at 20:46
  • The code you've provided works fine when I copy it into my python 2.7 console... so the issue lies elsewhere. Follow the link from GingerPlusPlus and provide more information – TemporalWolf Jun 24 '16 at 20:50
  • 1
    The python code provided doesn't work fine, it produces an IndexError, because you can't access any index in an empty list. The TypeError must be the result of some other portion of the code. So either the error message is not right, or the minimal example is not right. – Mel Jun 24 '16 at 20:57

1 Answers1

4

Python hasn't a safe get so you should change your code this way:

primes = []

if primes and primes[len(primes) - 1] > 3:
    ...

Even better, to get the last of the list you can use primes[-1]

primes = []

if primes and primes[-1] > 3:
    ...
Martin Forte
  • 774
  • 13
  • 17
  • To test that a list is not empty, you can simply use `if myList`, and to access the last element of a list you can use `myList[-1]`. – Mel Jun 24 '16 at 20:58
  • 2
    See also [Why list doesn't have safe “get” method like dictionary?](http://stackoverflow.com/q/5125619/120999) – Xiong Chiamiov Jun 24 '16 at 21:55