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']
7
  • 2
    [int(year) for year in birth_years if year] Commented Aug 8, 2018 at 11:21
  • 1
    You can either use a list comprehension or a try ... except. Not both. Commented Aug 8, 2018 at 11:24
  • 1
    You can't use a try-except in a comprehension, you could do it in a regular for loop Commented Aug 8, 2018 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) Commented Aug 8, 2018 at 11:28
  • 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) Commented Aug 8, 2018 at 11:43

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

2
converted_years = [int(year) for year in birth_years if year]

Comments

1
converted_years = [int(x) for x in birth_years if x.isdigit()]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.