Reputation: 2293
If have this list here:
[25, 8, 22, 9]
How can I make the program create 2 seperate lists, and print them both? One should contain all the numbers less than 20, and the other needs to contain all the numbers greater than 20. The final print result should be displayed like this: [8, 9]
, [25, 22]
Upvotes: 1
Views: 134
Reputation: 2253
li = [25, 8, 22, 9]
li.sort()
for i, x in enumerate(li):
if x > 20:
print li[:i]
print li[i:]
break
Upvotes: -2
Reputation: 40717
Note: the assumes you want twenty in listTwo
listOne = [x for x in yourList if x < 20]
listTwo = [x for x in yourList if x >= 20]
print listOne
print listTwo
Although you should use list comprehensions you might be interested in the for loop approach if you are starting with python
listOne = []
listOne = []
for x in yourList:
if x < 20:
listOne.append(x)
else:
listTwo.append(x)
Upvotes: 1
Reputation: 64563
a = [25, 8, 22, 9]
print [x for x in a if x > 20]
print [x for x in a if x < 20]
You use here list comprehensions. List comprehension looks like:
[ f(x) for x in a if cond(x) ]
That means: produce me a list that consists of f(x)
for each element of x
for that cond(x)
is True
.
In our case f(x)
is simply x
. And cond(x)
is x > 20
or x < 20
(please note also that if you have 20s in your list, they will disappear from the result).
If it is a homework you can solve the task in more low-level way:
a = [25, 8, 22, 9]
list1 = []
list2 = []
for elem in a:
if elem > 20:
list1.append(elem)
if elem < 20:
list2.append(elem)
print list1
print list2
Here you iterate through the list and check its elements. That elements that are greater than 20 you append to one list; and that that are lesser thatn 20 — to the other.
Upvotes: 1
Reputation: 304215
>>> predicates = lambda x:x<20, lambda x:x>20
>>> print [filter(pred, [25, 8, 22, 9]) for pred in predicates]
[[8, 9], [25, 22]]
Upvotes: 5
Reputation: 50185
def print_split_list(raw_list, split_value):
lower_list = [v for v in raw_list if v < split_value]
upper_list = [v for v in raw_list if v >= split_value]
print lower_list, upper_list
print_split_list([25, 8, 22, 9], 20) # => [8, 9] [25, 22]
Upvotes: 1
Reputation: 362786
Use list comprehensions:
>>> L = [25, 8, 22, 9]
>>> [x for x in L if x < 20]
[8, 9]
>>> [x for x in L if x > 20]
[25, 22]
Upvotes: 4