Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

dict.remove(True) removes int from list rather than boolean value

This script removes all items that are not integers from list List containing different data types: str, int, bool, float, list:

list = ["a", "b", 1, 2, True, False, 3.0, 4.0, [1, 2, 3], ["a","b"]]

'remove' list will contain the items that will be removed from the 'list' list remove=[]

If not of int type append 'remove' list with value for i in list: if type(1) != type(i): remove.append(i)

'remove' list is now which is exactly what we want: ['a', 'b', True, False, 3.0, 4.0, [1, 2, 3], ['a', 'b']]

Go through items in the 'remove' list and remove these item from the 'list' list for i in remove: list.remove(i)

print(list)

the result is [2, True] expected [1, 2]

When looping through the 'remove' list and i is True, it will remove 1 from the 'list' list rather than removing True. Can anyone clarify this behavior?

In other words how can I remove True from the below list not using "del list(index)" ['a', 'b', 1, 2, True, False, 3.0, 4.0, [1, 2, 3], ['a', 'b']]

1 Answer

Steven Parker
Steven Parker
243,656 Points

In Python, 1 and True are equal. But they are not identical.

You can explicitly check their type (int vs. boolean), or you could compare them using the identity comparator ("is").

The suggestion to "go through items" could imply something other than a simple remove. Can you think of another way to get rid of items that will give you the opportunity to test them first?