I'm new to Python and was learning about Lists and data types. I created a list and tried to separate integers and strings from the list using the type() function.
A = [1, 2, 'ABC', 'DEF',5]
B = []
for i in A:
if type(i) == str:
B.append(i)
A.remove(i)
print(A)
OP:
[1, 2, 'DEF', 5]
While it works as expected for most of the part, it does NOT append 'DEF' or any string I place at index A[3] to B. I checked the type, and it's str.
I'm using Pycharm but have tried doing this on online interpreters as well. Gives the same result. I have also added more elements to the list but it works as expected for elements added after that.
I have also tried doing the reverse and filtering out integers instead of strings.
A = [1, 2, 'ABC', 'DEF',5, 'GHI', 7]
B = []
for i in A:
if type(i) == int:
#print(i)
B.append(i)
A.remove(i)
print(A,B, sep='\n')
OP:
[2, 'ABC', 'DEF', 'GHI']
[1, 5, 7]
Even this approach leaves out the second element as shown in the output. What is the associated concept that I have overlooked?