3

Using Python 3.7, I have two lists, one nested and one that is not, and I would like to extract the strings that are ordered in one list, and place each into a corresponding ordered nested list. Once the nested lists have been merged, I plan to unpack them into a table.

I have tried to perform a nested for-loop where I iterate through the nested loop to isolate the nested lists, and then a second for loop to extract each string object from its regular (unnested) list. My attempts to insert the string into the nested list end up either iterating through each character in the string, or it adds the entire list of strings into the nested lists. I've tried some different list comprehension attempts with zip, but being new at Python I've not yet mastered the syntax to traverse the lists.

A very simple attempt that hopefully explains what I am trying to accomplish.

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = ['1-10', '10-20', '20-30']

for i in a:
  for j in b:
    i.insert(0, j)
print(a)
>>> [['1-10', 1, 2, 3], ['10-20', 4, 5, 6], ['20-30', 7, 8, 9]]

2 Answers 2

2

Use zip in a list-comprehension:

[[y] + x for x, y in zip(a, b)]

Example:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = ['1-10', '10-20', '20-30']

print([[y] + x for x, y in zip(a, b)])
# [['1-10', 1, 2, 3], ['10-20', 4, 5, 6], ['20-30', 7, 8, 9]]
Sign up to request clarification or add additional context in comments.

2 Comments

That really helps me understand getting into the nest with comprehension, thank you. Is there any way to update the list 'a' instead of printing its concatenation?
@sovgott, you can always assign it back to a instead of printing: a = [...].
1

Or use unpacking:

print([[y, *x] for x, y in zip(a, b)])

Output:

[['1-10', 1, 2, 3], ['10-20', 4, 5, 6], ['20-30', 7, 8, 9]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.