Split a list with Python


#1

Hi there,

I have been learning Python and have got this far (see below). What I am trying to do is split a list of numbers into 3 lists, small numbers in list1, medium in list2 and large in list3 etc. Hopefully this makes sense. When I run numbers through the Python component they don’t seem to adhere to the greater than or smaller than rules:

Any help appreciated!

Split lists with Python


#2

I would have thought that the following should be able to complete the task for you and is probably simpliar.

 

Note: make sure there is a indent prior to the output lines

 

 

Python Code:

for list in IN[0]:

output.append(list[0 : 96])

output.append(list[97 : 103])

output.append(list[104 : len(list)])


#3

You’ve written “list < 104” instead of “i <104”


#4

Capture

Thanks for the help guys,

I want to keep it the way I’m learning at the moment with if / else statements, and once that makes sense I can look at other methods. The result still doesn’t split into the 3 sublists, have I got some notation wrong somewhere? It looks to me that the script is thinking that all numbers are ‘less than 97’. Do I need to define the incoming stream of numbers as integers?

Thanks,

 


#5

The code is functioning as expected. You’re currently evaluating the index of the list, not the content of the list. Try replacing “i” with “list[i]” in the evaluation. Or instead of using a range loop, loop directly through the content of the list:

for number in list:

if number < 97 :

elif number >= 97 and <104:

else:

 


#6

also, please don’t name your variable “list” because its a name of the built in function called list(). It may cause unexpected behavior as well as general confusion and is considered poor programming habit. :slight_smile:


#7

Thanks for the input everyone! I’ve got the script to do what I want now, including giving me the index position of the list being sorted. I’m certain there are more efficient ways to do this, if you have any pointers I would be happy to hear them! Otherwise thank you for helping me get this working :slight_smile:

Split List Python