how to combine two orderd lists into a list of lists

1743 views python-3.x

I'm trying to writ a function that adds sequence numbers to each item in a list

example function(['a', 'b', 7]) output---> [(1, 'a'), (2, 'b'), (3, 7)]

currently I have

def example(el2):
    new=list(map((lambda LL: [el1,LL]),el2))
    return new

but it gives me

[[[0, 1, 2], 'a'], [[0, 1, 2], 'b'], [[0, 1, 2], 7]] 

not the desired output

answered question

2 Answers


There's lots of ways to do this, a simple way is to iterate over the input list with a counter. Basically the output is the (item-count, item), so this seems a good way forward.

input_list = ['a', 'b', 7 ]

def example(el2):
    output = []
    for i in range(len(el2)):
        output.append((i+1, el2[i]))
    return output


I'm not a big fan of lambda functions (in any programming language), as (IMMHO) they make for less-readable code.

posted this

You can use list comprehension:

input_list = ['a', 'b', 7]
output_list = [(i,e) for i, e in enumerate(input_list, start=1)]

or using a function:

def example(input_list):
    return [(i,e) for i,e in enumerate(input_list, start=1)]

output_list = example(input_list)

posted this

Have an answer?


Please login first before posting an answer.