Question
Asked By – Pav Ametvic
Consider the following Python code with which I add in a new list2
all the items with indices from 1 to 3 of list1
:
for ind, obj in enumerate(list1):
if 4 > ind > 0:
list2.append(obj)
How would you write this using list comprehension, if I have no access to the indices through enumerate?
something like:
list2 = [x for x in list1 if 4 > ind > 0]
but since I have no ind
number, would this work?
list2 = [x for x in enumerate(list1) if 4 > ind > 0]
Now we will see solution for issue: In Python list comprehension is it possible to access the item index?
Answer
list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]
This question is answered By – Pavel Anossov
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0