Home > Net >  Create multiple lists containing information from a single list
Create multiple lists containing information from a single list

Time:10-07

I have a list of strings of numbers, like this

["1", "2 3", "4 5 6"]

I want to turn this list into multiple other lists, so it will look like this

["1"] ["2 3"] ["4 5 6"]

with each of those being a separate list. How can I do this?

For context, these strings will be split and turned into integers so the final product will end up as

[1] [2,3] [4,5,6]

but that is not a part of this question, since I know how to get from step 2 to step 3.

I have found a somewhat similar post, but I can't figure out how to use dictionaries or list comprehensions like the answer suggests. I know how dictionaries work pretty well, but I am a little shaky on list comprehensions, so I apologize if there is an easy way to do it with that. Searching things like "create multiple lists in for loop python" and "make lists from other lists python" really only lead me to the post linked earlier.

CodePudding user response:

You can do this:

sample = ['1', '2 3', '4 5 6']
new_list = []

for i in sample:
     new_list.append([i])

This gives you the output:

[['1'], ['2 3'], ['4 5 6']]

However, your whole goal can be accomplished succinctly in this same loop:

for i in sample:
     new_list.append([int(j) for j in i.split()])

For the output:

[[1], [2, 3], [4, 5, 6]]

If you wanted to get even more Pythonic (albeit slower by my testing), you could do:

new_list = [[int(j) for j in i.split()] for i in sample]

CodePudding user response:

It's probably best to store the new lists in a list or dictionary. If you go the list route, you could say

[[s] for s in ["1", "2 3", "4 5 6"]]

The variable s becomes each string, and the [s] puts it in a list.

That code gives you

[['1'], ['2 3'], ['4 5 6']]
  • Related