Unable to list after filter

When I run this code:

arr = list(filter(lambda x: x > 0, arr))
for index, item in arr:
  # do something

I get this error

TypeError: 'int' object is not iterable

That doesn't make sense because I have listnot a int. Testing arrgives:

>>> print(arr)
[822]
>>> print(type(arr))
<class 'list'>
>>> print(len(arr))
1

Although there are many questions regarding this type of error, no one here explains this case. What could be wrong?

+4
source share
2 answers

The problem is not that filterit is not iterable, but rather the fact that you do the unpacking in the for loop header:

for index, item in arr:
  # do something

arr , ( index, item "" , Python index, item = 1?). enumerate(..), :

for index, item in enumerate(arr):
  # do something

enumerate(..) , ( ), - . , enumerate([1, 'a', 25]) (0, 1), (1, 'a'), (2, 25).


, item index:

for item in arr:
  # do something
+6

enumerate, :

arr = list(filter(lambda x: x > 0, arr))
for index in range(len(arr)):
    item = arr[index]
    # do something with item and index

, , , .

0
source

Source: https://habr.com/ru/post/1691566/


All Articles