-1

Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

  • sounds like a great time to use a for loop. – Pintang Nov 17 '17 at 16:35
  • `zip()` would be useful here too. – Daniel Roseman Nov 17 '17 at 16:36
  • 4
    Possible duplicate of [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – Bill the Lizard Nov 17 '17 at 16:37
  • @BilltheLizard For that link you provided, it is relevant, but I didn't want the budget to be printed out. I want purely the years. Would it be possible with that method? From what I can see, I think it can be, but I'm not entirely sure. – Andy Tran Nov 17 '17 at 16:40
  • Yes, inside the loop you would just compare the budget to 0 and print the year (or append it to another list... whatever you need to do with it). – Bill the Lizard Nov 17 '17 at 16:41

3 Answers3

0
budgets = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

for budget, year in zip(budgets, years):
    if budget < 0:
        nodef.append(year)

print(nodef)
C0DY
  • 191
  • 1
  • 7
  • This worked perfectly! Thank you for the help! I didn't know zip() was a thing so I will look into using that for the future. – Andy Tran Nov 17 '17 at 16:41
0

If you want to restrict output to 21 this would do it:

nodef = [year for budget, year in zip(budgets, years) if budget < 0][:21]

Leave out the [:21] if you don't really need it.

And another approach:

nodef = [years[i] for i, budget in enumerate(budgets) if budget < 0]
zipa
  • 27,316
  • 6
  • 40
  • 58
0

Another way of doing it would be:

nodef = list(map(lambda k: years[k], filter(lambda i: budget[i]<0, range(len(budget)))))
print(nodef)

It produces the following output:

[2000, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29