user4001386
user4001386

Reputation:

Add a value from a list to the end of a value in another list in Python

I am sure that this is a basic task and that the answer is somewhere on google but the problem I have is that I don't know what this is "called" so I am having a bad time trying to google it, almost every page demonstrates merging two lists which is not in my interest.

I basically have two lists where I would like to add the values from the list "add" to the the end of each word in the list "stuff" and print it out.

 add = ['123', '12345']
 stuff = ['Cars', 'Suits', 'Drinks']

Desired output

    Cars123
    Cars12345
    Suits123
    Suits12345
    Drinks123
    Drinks12345

Thanks in advance, and sorry again for bad research.

Upvotes: 1

Views: 53

Answers (4)

Bill Bell
Bill Bell

Reputation: 21643

Ignore what I said about combinations in the comment!

>>> from itertools import product
>>> add = ['123', '12345']
>>> stuff = ['Cars', 'Suits', 'Drinks']
>>> for a, s in product(add, stuff):
...     a+s
...     
'123Cars'
'123Suits'
'123Drinks'
'12345Cars'
'12345Suits'
'12345Drinks'

Addendum: Timing information: This code, which compares the nested loop with the product function from itertools does indeed show that the latter takes more time, in the ratio of about 2.64.

import timeit

def approach_1():
    add = ['123', '12345']; stuff = ['Cars', 'Suits', 'Drinks']
    for a in add:
        for s in stuff:
            a+s

def approach_2():
    from itertools import product
    add = ['123', '12345']; stuff = ['Cars', 'Suits', 'Drinks']
    for a, s in product(add, stuff):
        a+s

t1 = timeit.timeit('approach_1()','from __main__ import approach_1', number=10000)
t2 = timeit.timeit('approach_2()','from __main__ import approach_2', number=10000)

print (t2/t1)

Upvotes: 1

ANIRUDH M S
ANIRUDH M S

Reputation: 31

Try this :

for i in stuff:
    for j in add:
        print(i+j)

Let me know if it works

Upvotes: 0

marcos
marcos

Reputation: 4510

You need two for loops for that:

for stuff_element in stuff:
    for add_element in add:
         print(stuff_element+add_elements)

Upvotes: 0

nathan.medz
nathan.medz

Reputation: 1603

Is there any reason you can't just use a nested loop? It's certainly the simplest solution.

for i in stuff:
    for j in add:
        print(i+j)

gives

Cars123
Cars12345
Suits123
Suits12345
Drinks123
Drinks12345

This assumes that both lists are strings.

As a side point, shadowing function names like add is generally a bad idea for variables, so I would consider changing that.

Upvotes: 1

Related Questions