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]
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)
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]
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)