1

I'm reading some python code and I came across a line of code that says arr = [-1]*n where arr is an array and n is an integer. What does this notation mean? What would arr look like after this?

I feel bad asking this question here, because it feels more like a question for google, but I can't find anything on google by just googling the line of code, and I don't know the name of the notation.

7
  • 2
    "What would arr look like after this?" It would look like print(arr). Commented Apr 5, 2018 at 21:08
  • 1
    You could just try it out in the interactive interpreter Commented Apr 5, 2018 at 21:08
  • 1
    I'd suggest you to use python console for simple statements like this one Commented Apr 5, 2018 at 21:08
  • 1
    Have you tried running it to see what happens? Commented Apr 5, 2018 at 21:09
  • 2
    BTW, in Python these are called lists, not arrays. Commented Apr 5, 2018 at 21:10

2 Answers 2

3

It means, that the resulting array will be that cell repeated n times. In other words it will return an array with n elements when the initial array had one element. Every one of them will be -1 in this case.

In general it will produce an array repeated n-times, for example [1, 2, 3] * 2 == [1, 2, 3, 1, 2, 3].

Sign up to request clarification or add additional context in comments.

1 Comment

One point of clarification: your answer seems to be implying that the result will always have length n. Could you update your answer to make clear that, for example [1, 2] * 2 == [1, 2, 1, 2]?
2
arr = ['z', 'r', 't']
n = 5
arr = [-1] * n
print arr

'''
[-1, -1, -1, -1, -1]
'''

# the values of 'arr' have been changed

1 Comment

Even if arr = [] the answer would still be [-1, -1, -1, -1, -1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.