user3499023
user3499023

Reputation: 21

Python: Combining two lists to make a new list

I would like to combine two lists in Python to make one list in the following way:

Input:

list1 = [a, b, c, d]
list2 = [1, 2, 3, 4]

Result should be:

list3 = [a1, a2, a3, a4, b1, b2, b3, b4, c1 ... ] 

Upvotes: 1

Views: 1202

Answers (2)

marillion
marillion

Reputation: 11170

Or using list comprehension as a one liner, instead of nested loops:

list1 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4]
list3 = [x + str(y) for x in list1 for y in list2]

Note: I assume you forgot the quotes in list1, and list3 is supposed to be a list of strings.

Upvotes: 4

DeeTee
DeeTee

Reputation: 707

list1 = ['a','b','c','d']
list2 = [1,2,3,4]
list3 = []
for letter in list1:
    for number in list2:
        newElement = letter+str(number)
        list3.append(newElement)
print list3

returns this: ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3', 'd4']

Upvotes: 2

Related Questions