Python editing lists and converting to a dictionary After validation my errors list returns

[(False, {u'first_name': u'First name is too short'}), (False, {u'last_name': u'Last name is too short'}), (False, {u'confirm_password': u'Password is too short'}), (False, {u'email': u'Please enter a valid email'})]


I use a for loop to create a new list and only add the one index in every element.  I am trying to get rid of every False.  I am looking for a way to improve my code.

Here is my code

errors = []
errors.append(self.validate_length(first_name, 'first_name', 2, "First name is too short"))
errors.append(self.validate_length(last_name, 'last_name', 2, "Last name is too short"))
errors.append(self.password_match(password, confirm_password))
errors.append(self.validate_email(email_address))

error = []
print errors
for elements in range(0, len(errors)):
    try:
        errors[elements][1]
        error.append(errors[elements][1])
    except:
        pass
I have a few complaints:


You're using a for loop to iterate over the indexes of a list instead of directly iterating over the list, but you're not actually using the indexes for anything. I'd suggest

for element in errors:


instead, then using element instead of errors[elements]
The line errors[elements][1] doesn't actually appear to do anything, except throw an IndexError if the list is length 1 or shorter. If this is the intended behaviour, it could be made clearer using a check such as if len(errors[elements]) &lt; 2: ..., and perhaps avoid using exceptions entirely.
An except which catches every type of error there is is rarely a good idea - it's unclear and risks swallowing exceptions you actually want to be warned about in the future. If I understand your code correctly, except IndexError would do the same thing, but be slightly clearer.


All in all, however, it appears you're using exceptions for a case where they aren't needed, which tends to make code harder to grok overall. I'd probably rewrite the loop to something along the lines of

for element in errors:
    if len(element) &gt;= 2:
        error.append(element[1])


though a list comprehension such as error = [element[1] for element in errors if len(element) &gt;= 2] could work too.