2

I have the two following nested lists

List 1: [["Bob", "Davon", "Alex"],["Dylan","Rose", "Hard"]] 

List 2: [["Red", "Black"] , ["Blue", "Green"], ["Yellow", "Pink"]]

And want to show the first word of each list within the nest together, the second etc. So that the outcome would be:

['Bob and Dylan', 'Davon and Rose', 'Alex and Hard'] --> for the first list

['Red and Blue and Yellow, 'Black and Green and Pink'] --> for the second list

So the first outcome I can get with the following code

name_list = [["Bob", "Davon", "Alex"],["Dylan","Rose", "Hard"]] 

def addition(name_list):    
    new_list = []
    for i in range(len(name_list)):
        for j in range(len(name_list[i])):
            new_list.append(name_list[i][j] + " and " + name_list[i+1][j])
        return new_list       

addition (name_list)

But the second list: [["Red", "Black"] , ["Blue", "Green"], ["Yellow", "Pink"]] does not provide the right outcome.

1
  • 1
    The answers below both give the right idea, although I don't think they explicitly make the main point which should be that zip(*my_list) transposes your lists of lists into new versions which are then easy to manipulate into the detailed strings you want. Commented Oct 2, 2019 at 21:17

2 Answers 2

1
names_list = ["{} and {}".format(*t) for t in zip(*name_list)]
colors_list = ["{} and {}".format(*t) for t in zip(*color_list)]

This probably won't work on python2.7 and you're better off upgrading to python3 anyways, since python2 is reaching end of life

Sign up to request clarification or add additional context in comments.

2 Comments

Works fine in Python 2.7 for me.
There are three pair being zipped for color_list, so you actually need ["{} and {} and {}".format(*t) for t in zip(*color_list)]
0
[' and '.join(x) for x in zip(*name_list)]
[' and '.join(x) for x in zip(*color_list)]

str.join() will work on a list of any size, placing the string between each item.

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.