Skip to content

How to Fill an Array in Python

The challenge

We want an array, but not just any old array, an array with contents!

Write a function that produces an array with the numbers  to N-1 in it.

For example, the following code will result in an array containing the numbers  to 4:

arr(5) # => [0,1,2,3,4]
Code language: Python (python)

Note: The parameter is optional. So you have to give it a default value.

The solution in Python code

Option 1:

def arr(n=): return [x for x in range(n) if n>]
Code language: Python (python)

Option 2:

def arr(n=): return list(range(n))
Code language: Python (python)

Option 3:

def arr(n=): aux = [] for x in range(n): aux.append(x) return aux
Code language: Python (python)

Test cases to validate our solution

import test from solution import arr"Basic Tests") def basic_tests():'Basic Test Cases') def basic_test_cases(): test.assert_equals(arr(4), [,1,2,3]) test.assert_equals(arr(), []) test.assert_equals(arr(), [])
Code language: Python (python)

See also  How to Calculate the Least Common Multiple in Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x