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 @test.it("Basic Tests") def basic_tests(): @test.it('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
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x