Separating Integers and Strings From a List

Viewed 82

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?

2 Answers

You could use list comprehension:

raw_list = [1, 2, 'ABC', 'DEF',5, 'GHI', 7]
A = [x for x in raw_list if type(x) == str]
B = [x for x in raw_list if type(x) == int]
print(A, B, sep = '\n')

Output:

['ABC', 'DEF', 'GHI']
[1, 2, 5, 7]

The best way is to use filter function:

x = [1, 2, 'ABC', 'DEF',5, 'GHI', 7]
digits = list(filter(lambda e: isinstance(e, int), x))
strings = list(filter(lambda e: isinstance(e, str), x))
print(digits)
print(strings)
Related