Usar any() com isinstance()
Nesta etapa, você aprenderá como usar a função any() em combinação com a função isinstance() para verificar se uma lista contém pelo menos um elemento de um tipo específico. Isso é particularmente útil ao trabalhar com listas de tipos mistos.
A função any() retorna True se qualquer elemento em um iterável (como uma lista) for verdadeiro. Caso contrário, retorna False. A função isinstance() verifica se um objeto é uma instância de uma classe ou tipo especificado.
Vamos criar um script Python para demonstrar isso. No editor VS Code, crie um novo arquivo chamado any_isinstance.py no diretório ~/project.
## Create a mixed-type list
my_list = [1, "hello", 3.14, True]
## Check if the list contains any integers
has_integer = any(isinstance(x, int) for x in my_list)
## Print the result
print("List contains an integer:", has_integer)
## Check if the list contains any strings
has_string = any(isinstance(x, str) for x in my_list)
## Print the result
print("List contains a string:", has_string)
## Check if the list contains any floats
has_float = any(isinstance(x, float) for x in my_list)
## Print the result
print("List contains a float:", has_float)
## Check if the list contains any booleans
has_bool = any(isinstance(x, bool) for x in my_list)
## Print the result
print("List contains a boolean:", has_bool)
Salve o arquivo. Agora, execute o script usando o comando python no terminal:
python ~/project/any_isinstance.py
Você deve ver a seguinte saída:
List contains an integer: True
List contains a string: True
List contains a float: True
List contains a boolean: True
Neste exemplo, usamos uma expressão geradora (isinstance(x, int) for x in my_list) dentro da função any(). Essa expressão geradora produz True se um elemento x é uma instância de int, e False caso contrário. A função any() então verifica se algum desses valores é True.
Vamos modificar a lista para ver como a saída muda. Mude o primeiro elemento de my_list para um float:
## Create a mixed-type list
my_list = [1.0, "hello", 3.14, True]
## Check if the list contains any integers
has_integer = any(isinstance(x, int) for x in my_list)
## Print the result
print("List contains an integer:", has_integer)
## Check if the list contains any strings
has_string = any(isinstance(x, str) for x in my_list)
## Print the result
print("List contains a string:", has_string)
## Check if the list contains any floats
has_float = any(isinstance(x, float) for x in my_list)
## Print the result
print("List contains a float:", has_float)
## Check if the list contains any booleans
has_bool = any(isinstance(x, bool) for x in my_list)
## Print the result
print("List contains a boolean:", has_bool)
Salve o arquivo e execute-o novamente:
python ~/project/any_isinstance.py
A saída agora deve ser:
List contains an integer: False
List contains a string: True
List contains a float: True
List contains a boolean: True
Agora, a lista não contém nenhum inteiro, então has_integer é False.
Essa técnica é útil para validar o conteúdo de uma lista ou para realizar diferentes ações com base nos tipos de elementos presentes na lista.