Search code examples
pythonlistintegerquotes

Python go from a list of tuple to a list of integer without quotes


I have this code :

selected_listbox_select_criteria_column = [('0', 'firstName'),('1', 'lastName'),('2', 'phone')]

column_to_check_for_criteria = []

column_to_check_for_criteria(', '.join(elems[0] for elems in selected_listbox_select_criteria_column))

It gives me this result :

['0,1,2']

How can I have a strict list of integer like this :

[0,1,2] 

without the quotes to finally get equivalent of : column_to_check_for_criteria = [0,1,2]

Thanks


Solution

  • The issue you are facing is the additional work you don't need to be doing with your ', '.join(...) call. It seems what you are trying to do is to simply extract in to a list the integer values as integer type from your list of tuples. To do this, based on the code you are writing, you don't need to use that join. You can simply use a list comprehension and cast each elems[0] to int. This should give you the expected output:

    selected_listbox_select_criteria_column = [('0', 'firstName'),('1', 'lastName'),('2', 'phone')]
    
    column_to_check_for_criteria = [int(elems[0]) for elems in selected_listbox_select_criteria_column]
    

    Running that will now give you

    [0, 1, 2]
    

    As added information, you would typically use a join when you want to turn a list in to a string. An extra little note about using join is that expects an iterable of type string and not int. You can't actually use it on a list of integers. Observe the following two examples:

    This will fail

    a = [1, 2, 3]
    print(",".join(a))
    

    This will not

    a = ["a", "b", "c"]
    print(",".join(a))