Divide Python list into multiple lists based on element condition

Question:

How can I take a python list and divide it into multiple lists based on element conditions?

myList = ['Georgia', 12344, 52353, 'Alabama', 352947, 394567, 123437, 'Florida', 992344, 788345]




for each in myList:
  do stuff

result:

list1 = ['Georgia', 12344, 52353,]
list2 = ['Alabama', 352947, 394567, 123437]
list3 = ['Florida', 992344, 788345] 
Asked By: PinAppleRedbull

||

Answers:

Use isinstance to check if it’s a string or int. Start a new sublist or append to the sublist depending on condition.

newlists = []

for item in myList:
    if isinstance(item, str):
        new_sublist = [item]
        newlists.append(new_sublist)
    else:
        new_sublist.append(item)
Answered By: Michael Cao
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.