-1

I need to create an array with the same data from another array but just the positive values.

I was trying this code below:

if a > 0:
    arr = a
Prune
  • 76,765
  • 14
  • 60
  • 81
  • 1
    If you Google the phrase "Python filter list", you’ll find tutorials that can explain it much better than we can in an answer here. – Prune Oct 17 '18 at 18:07
  • Yes, filter is the correct search term. This is also very popular to do with a list comprehension: `[a for a in arr if a > 0]`. Have a look at list comprehensions. They are very pythonic! – Anton vBR Oct 17 '18 at 18:09
  • https://stackoverflow.com/q/3013449/1358308 looks useful – Sam Mason Oct 17 '18 at 19:17

1 Answers1

0

Here two possible options:

Option 1: Initialize an empty list that is going to contain the array with positive numbers:

array1 = [1, 2, -1, -3, 5, 6, -9]

array2 = []
for item in array1:
    if item > 0:
        array2.append(item)

Option 2:

Use a list comprehension to create the second array:

array1 = [1, 2, -1, -3, 5, 6, -9]
array2 = [item for item in array1 if item > 0]

In both cases the output will be:

print(array2)
==> [1, 2, 5, 6]
virtualdvid
  • 2,323
  • 3
  • 14
  • 32