0

I have a list with years as strings but there are few missing years which are represented as empty strings.

I am trying to convert those strings to integers and skip the values which can't be converted using list comprehension and try and except clause?

birth_years = ['1993','1994', '' ,'1996', '1997', '', '2000', '2002']

I tried this code but it's not working.

try:
    converted_years = [int(year) for year  in birth_years]
except ValueError:
    pass

required output:
converted_years = ['1993','1994','1996', '1997', '2000', '2002']
Sai Kumar
  • 665
  • 2
  • 9
  • 21
  • 2
    [int(year) for year in birth_years if year] – Chris_Rands Aug 08 '18 at 11:21
  • @Chris_Rands How can I use try and except clause with pass statement to achieve this? – Sai Kumar Aug 08 '18 at 11:23
  • 1
    You can either use a list comprehension or a `try ... except`. Not both. – Aran-Fey Aug 08 '18 at 11:24
  • 1
    You can't use a try-except in a comprehension, you could do it in a regular for loop – Chris_Rands Aug 08 '18 at 11:24
  • 1
    Of course you could create a separate function that perform the try-except and then call that in the comprehension but I don't see any point (for this simple example at least) – Chris_Rands Aug 08 '18 at 11:28
  • @Chris_Rands can you tell me how to do that for learning purpose? – Sai Kumar Aug 08 '18 at 11:36
  • 1
    write a function like `def my_f: try: return int(year); except ValueError: pass` then in the comprehension `[my_f(year) for year in birth_years if my_f(year) ]` (the pass means the fasly None is returned when the error is encountered, not this isn't the most efficient to call the function twice) – Chris_Rands Aug 08 '18 at 11:43

3 Answers3

6

[int(year) for year in birth_years if year.isdigit()]

Ankit S
  • 505
  • 5
  • 9
2
converted_years = [int(year) for year in birth_years if year]
Mohit Solanki
  • 2,122
  • 12
  • 20
1
converted_years = [int(x) for x in birth_years if x.isdigit()]
Madhan Varadhodiyil
  • 2,086
  • 1
  • 14
  • 20