1
def check(temp):
  for i in temp:
    if type(i) == str:
      temp.remove(i)

temp = ['a', 'b']
print(temp)    ==> Output: ['a','b']
check(temp)
print(temp)    ==> Output: ['b']

When run with

temp = [ 'a', 1 ], Output is [1]

temp = [ 1, 'a', 'b', 'c', 2 ], Output is [ 1, 'b', 2 ]

Could someone care to explain how the result is evaluated.. Thnx

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504

3 Answers3

5

You are modifying the list while iterating it. It will skip elements because the list changes during the iteration. Removing items with list.remove() will also remove the first occurence of that element, so there might be some unexpected results.

The canonical way of removing elements from a list is to construct a new list, like so:

>>> def check(temp):
...    return list(x for x in temp if not isinstance(x, str))

Or you could return a regular list comprehension:

>>> def check(temp):
...     return [x for x in temp if not isinstance(x, str)]

You should generally test for types with isinstance() instead of type(). type has no idea about inheritance for example.

Examples:

>>> check(['a', 'b', 1])
[1]

>>> check([ 1, 'a', 'b', 'c', 2 ])
[1, 2]

>>> check(['a', 'b', 'c', 'd'])
[]
msvalkon
  • 11,887
  • 2
  • 42
  • 38
  • @Aशwiniचhaudhary No reason, might as well use a list comprehension, I guess I've just recently written a lot of generator expressions. – msvalkon Apr 01 '14 at 06:48
  • @eryksun a naive ipython `%timeit` test for both functions with a list of ~200k elements shows a difference of ~3-5 ns. Sure it's slower but half the time seems like an exaggeration, unless I'm timing it wrong. – msvalkon Apr 01 '14 at 07:17
0

You can use ,

def check(temp):
    return [i for i in temp if type(i)!=str]

temp = [ 1, 'a', 'b', 'c', 2 ]

print check(temp)

Output:

[1, 2]

OR

def check(temp):
    return [i for i in temp if not isinstance(i, str)]

temp = [ 1, 'a', 'b', 'c', 2 ,"e",4,5,6,7]

print check(temp)

output:

[1, 2, 4, 5, 6, 7]
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
0
>>> text = ['a', 'b', 1, {}]
>>> filter(lambda x: type(x) == str, text)
['a', 'b']

function will be like:

>>> def check(temp):
...     return list(filter(lambda x: type(x) == str, temp))
... 
>>> check(text)
['a', 'b']
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71