Why does the type of i change to an int even when I printed its type and made sure it was str?

Question:

list_1 = ["adham","ayman","[email protected]",19]
email = []
for i in list_1:
    print(type(i))
    if "@" in i:
        email.append(i)
print(email)
Asked By: Adham Ayman

||

Answers:

use str() in the if condition to solve this problem because there is an integer value in your list_1.

when i reaches the last element of the list:19 then it throws the error.

Solution:

list_1 = ["adham","ayman","[email protected]",19]
email = []
for i in list_1:
    print(type(I))
    if "@" in str(I):
        email.append(i)
print(email)
Answered By: Dev

There is an int at index 3 in list_1, which is causing your program to fail due to a TypeError

Answered By: Daniel Odicho

You got int in the list, and you’re not converting the type to str by print(type(i)). Your if condition is expecting an iterable to check against, but getting an int for 19. You can update it to check against only for strings if you think there’s gonna be int in the list, if isinstance(i, str) and "@" in i, or if "@" in str(i) if you need to convert int to str first.

Answered By: Ash Nazg
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.