Back to Freecodecamp

Challenge 212: Array Insertion

curriculum/challenges/english/blocks/daily-coding-challenges-python/6994cff2290543b3aec9f511.md

latest1.4 KB
Original Source

--description--

Given an array, a value to insert into the array, and an index to insert the value at, return a new array with the value inserted at the specified index.

--hints--

insert_into_array([2, 4, 8, 10], 6, 2) should return [2, 4, 6, 8, 10].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(insert_into_array([2, 4, 8, 10], 6, 2), [2, 4, 6, 8, 10])`)
}})

insert_into_array(["the", "quick", "fox"], "brown", 2) should return ["the", "quick", "brown", "fox"].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(insert_into_array(["the", "quick", "fox"], "brown", 2), ["the", "quick", "brown", "fox"])`)
}})

insert_into_array([], 0, 0) should return [0].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(insert_into_array([], 0, 0), [0])`)
}})

insert_into_array([0, 1, 1, 2, 3, 8, 13], 5, 5) should return [0, 1, 1, 2, 3, 5, 8, 13].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(insert_into_array([0, 1, 1, 2, 3, 8, 13], 5, 5), [0, 1, 1, 2, 3, 5, 8, 13])`)
}})

--seed--

--seed-contents--

py
def insert_into_array(arr, value, index):

    return arr

--solutions--

py
def insert_into_array(arr, value, index):
    return arr[:index] + [value] + arr[index:]