-5

I'm new to python. Here's my file:

contiguous.py:

def fillArray(len, val):
    var arr = [], i
    for i = 0; i < len; i++:
        arr.append(val)
    return arr

I try to execute:

$ python contiguous.py
  File "contiguous.py", line 2
    var arr = [], i
          ^
SyntaxError: invalid syntax
$ python -V
Python 3.6.0

Why the error? What am I missing?

Web_Designer
  • 72,308
  • 93
  • 206
  • 262

4 Answers4

2

You don't have to declare a variable to use it in Python. You just instantiate. So you would want to write just arr = [] and nothing for i. Furthermore, your loop syntax is incorrect. You should write for i in range(len).

Ben Frankel
  • 174
  • 2
  • 5
1

Ok, your function in Python is:

def fillArray(len, val):
    arr = []
    for _ in range(len):
        arr.append(val)
    return arr

which is equivalent to:

def fillArray(len, val):
    return [val] * len

Which are both dangerous if val is mutable: Python is pass by assignment, so if you try to make an array of empty lists, via fillArray(len, []), you will have a bad day.

Community
  • 1
  • 1
TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
  • 1
    I prefer the term "call by sharing"... because sharing is caring! – juanpa.arrivillaga Mar 20 '17 at 22:35
  • @juanpa.arrivillaga Maybe that should become the official term. Fredrik Lundh's effbot article [call by object](http://effbot.org/zone/call-by-object.htm) mentions call by sharing as a synonym... ultimately that may be a better source for someone who may be confused by the topic. – TemporalWolf Mar 20 '17 at 22:47
  • 1
    Well, it is the term used by Barbara Liskov, when she invented it for [CLU](https://en.wikipedia.org/wiki/CLU_(programming_language)). But it is a rather unused term. Indeed, in Java, they just say call-by-value! Other things introduced in that language are iterators and constructors! – juanpa.arrivillaga Mar 20 '17 at 22:49
0

There is no var keyword in python. Simply remove that.

Variables are set with:

variable_x = []

Also, the way you set more than one variable per line in python is:

variable_x, i = [], 0

Also, your loop looks wrong. It should be:

for i in range(len):
meyer9
  • 1,120
  • 9
  • 26
0

You don't need the keyword var. To make arr an array, just do:

arr = []

Variables in python don't have types, only objects do. The type of a variable at any given moment is the type of the object they refer at that moment. So the line above initializes arr to an empty list, effectively making arr a list too. Also, some other considerations about your code: you are trying to fill an array with a value. There's a much easier way to do it:

arr = [val] * len

In this case you don't even need to do arr=[], your whole function can be replaced by the line above.

André Santos
  • 380
  • 1
  • 4
  • 12