AutomaticStatic
AutomaticStatic

Reputation: 1739

Python append value at array increment to a list

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']

Upvotes: 0

Views: 924

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

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)

Upvotes: 4

labheshr
labheshr

Reputation: 3056

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] )

Upvotes: 0

Related Questions