0

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] 
roganjosh
  • 12,594
  • 4
  • 29
  • 46

1 Answers1

2

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)
Michael Cao
  • 2,278
  • 1
  • 1
  • 13