Home > Net >  Create an array of even numbers from 2 to 20.Then using for loop and append function, insert numbers
Create an array of even numbers from 2 to 20.Then using for loop and append function, insert numbers

Time:09-24

Create an array of even numbers from 2 to 20. Then using for loop and append() function, insert all the numbers divisible by 7 from 30 to 50 to that array.

from array import *

for i in array('b',[x for x in range(2,21,2)]):
  for c in array('b',[x for x in range(35,51,7)]):

my_ar = i.append(c)

print(my_ar)

CodePudding user response:

The first requirement doesn't specify a loop so you can directly create a list from range.
For the second part you want to append to your previous list within your loop.

my_ar = list(range(2, 21, 2))
for num in range(35, 51, 7):
    my_ar.append(num)

Result

>>> my_ar
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 35, 42, 49]

If your requirement is to indeed use the array module, then similar approach

from array import array
my_arr = array('i', list(range(2, 21, 2)))
for num in range(35, 51, 7):
    my_arr.append(num)

Result

>>> my_arr
array('i', [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 35, 42, 49])

CodePudding user response:

As stated by others. I don't see the need to use the array module. But this can be done without a loop using list addition:

list(range(2, 21, 2))   list(range(35, 51, 7))

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 35, 42, 49]
  • Related