List Only Stops Once The Element Of The List Is The Number 7
Solution 1:
List comprehensions really are for making mapping/filtering combinations. If the length depends on some previous state in the iteration, you're better off with a for-loop, it will be more readable. However, this is a use-case for itertools.takewhile
. Here is a functional approach to this task, just for fun, some may even consider it readable:
>>>from itertools import takewhile>>>from functools import partial>>>import operator as op>>>list(takewhile(partial(op.ne, 9), [7,8,3,2,4,9,51]))
[7, 8, 3, 2, 4]
Solution 2:
You can use iter()
builtin with sentinel value (official doc)
l = [7,8,3,2,4,9,51]
sublist = [*iter(lambda i=iter(l): next(i), 9)]
print(sublist)
Prints:
[7, 8, 3, 2, 4]
Solution 3:
To begin with, it's not a good idea to use python keywords like list
as variable.
The list comprehension [x for x in list if x < 9]
filters out elements less than 9, but it won't stop when it encounters a 9, instead it will go over the entire list
Example:
li = [7,8,3,2,4,9,51,8,7]
print([x for x in li if x < 9])
The output is
[7, 8, 3, 2, 4, 8, 7]
To achieve what you are looking for, you want a for loop which breaks when it encounters a given element (9 in your case)
li = [7,8,3,2,4,9,51]
res = []
item = 9
#Iterate over the list
for x in li:
#If item is encountered, break the loop
if x == item:
break
#Append item to list
res.append(x)
print(res)
The output is
[7, 8, 3, 2, 4]
Post a Comment for "List Only Stops Once The Element Of The List Is The Number 7"