2

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?

petadata
  • 23
  • 3
  • 3
    Do not alter lists that you are iterating over – Mark Tolonen Dec 24 '21 at 18:39
  • 1
    I think that the problem is that you remove the item from the list you iterate on. You should iterate the list using index (with the range function). – SagiZiv Dec 24 '21 at 18:40
  • 1
    print(A) inside the loop you will get the answer. When you remove current element then in next pass it skips next element bcz inside loop its assuming that next element is the current element after you use remove() method. – Deepak Tripathi Dec 24 '21 at 18:49

2 Answers2

2

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]
Ben DeVries
  • 506
  • 3
  • 6
0

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)
Ratery
  • 2,863
  • 1
  • 5
  • 26