I want to write a code that contains a sublist , that only stops once the element of the list is a certain number , for example 9.
I´ve already tried using different operators , if statements .
def sublist (list):
return [x for x in list if x <9]
[7,8,3,2,4,9,51]
the output for the list above should be :
[7,8,3,2,4]
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 listExample:
The output is
To achieve what you are looking for, you want a for loop which breaks when it encounters a given element (9 in your case)
The output is
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:You can use
iter()
builtin with sentinel value (official doc)Prints: