Splitting lists into to different lists

Question:

I have a list:

list =  [['X', 'Y'], 'A', 1, 2, 3]

That I want to split into:

new_list = [['X','A', 1, 2, 3] , ['Y', 'A', 1, 2, 3]]

Is this possible?

Asked By: abh

||

Answers:

This probably not the best aproach but it works

l = [['X', 'Y'], 'A', 1, 2, 3]

new_list = []
to_append = []
for item in l:
    if isinstance(item, list):
        new_list.append(item)
        continue

    to_append.append(item)

new_list.append(to_append)
print(new_list)
Answered By: ShadowCrafter_01

Sure, take off the first element to create an outer loop, and then loop over the rest of the list to build the sub-lists:

lst = [['X', 'Y'], 'A', 1, 2, 3]

new_list = []

for item in lst[0]:
    sub = [item]
    for sub_item in lst[1:]:
        sub.append(sub_item)
    new_list.append(sub)

Or, as a comprehension:

new_list = [[item, *lst[1:]] for item in lst[0]]

Where the *lst[1:] will unpack the slice into the newly created list.

Borrowing that idea for the imperative for-loop:

new_list = []

for item in lst[0]:
    sub = [item, *lst[1:]]
    new_list.append(sub)
Answered By: C.Nivs

Yes, the code below returns exactly what you want.

list =  [['X', 'Y'], 'A', 1, 2, 3]
new_list = []

for i, item in enumerate(list[0]):
    new_list.append([item] + list[1:])

print(new_list)
Answered By: Danna

I’ll suggest a more concise approach that uses iterable unpacking — IMO it’s cleaner than using list slices.

We take the first element of lst and separate it from the rest of the list. Then, we use a list comprehension to create a new list for every element in the original sublist of lst:

lst = [['X', 'Y'], 'A', 1, 2, 3]
fst, *rest = lst

[[elem, *rest] for elem in fst]

This outputs:

[['X', 'A', 1, 2, 3], ['Y', 'A', 1, 2, 3]]
Answered By: BrokenBenchmark
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.