0

Let's say I have a list of lists:

name_list = ['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson']

I have another arbitrary list, let's say of colors:

color_list = ['Red', 'Green', 'Blue']

What's the simplest or most efficient way of appending a given number of colors to the names in rotation? For example, if I chose two colors the returned list would look like:

output_list = ['John', 'Smith', 'Red'], ['Sarah', 'Nichols', 'Green'], ['Alex', 'Johnson', 'Red']

or if I chose 3 colors:

output_list = ['John', 'Smith', 'Red'], ['Sarah', 'Nichols', 'Green'], ['Alex', 'Johnson', 'Blue']
1
  • 2
    Have you tried anything? Commented Oct 19, 2015 at 21:09

2 Answers 2

4

You can itertools.cycle a slice of the list:

name_list = [['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson']]


color_list = ['Red', 'Green', 'Blue']

from itertools import cycle, islice

i = 2 
cyc =  cycle(islice(color_list, 0, i))
for  sub in name_list:
    sub.append(next(cyc))


print(name_list)

Output:

[['John', 'Smith', 'Red'], ['Sarah', 'Nichols', 'Green'], ['Alex', 'Johnson', 'Red']]

You could also use the index as we iterate over name_list modulo i to extract the correct element from color_list:

name_list = [['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson'], ['Alex', 'Johnson']]

color_list = ['Red', 'Green', 'Blue']


i = 2
for ind, sub in enumerate(name_list):
    sub.append(color_list[ind % i])

print(name_list)
Sign up to request clarification or add additional context in comments.

1 Comment

@Pynchia, I had two answers and ended up mixing up both, enumerate is not needed at all for the first
0

First - your list of lists should look like this:

name_list = [['John', 'Smith'], ['Sarah', 'Nichols'], ['Alex', 'Johnson']]

you are missing the brackets...

one simple way would be to use modulo operator... (check for edge cases such as when color list is empty):

color_len = len(color_list)
for idx,elem in enumerate(name_list):
    elem.append( color_list[idx%color_len] )

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.