Search code examples
pythonlistoptimizationtupleslogic

how to transform a python list to a list of tuple in 1/2 lines?


Input: ['a','b','c','d','e']

Output: [('a','b'),('c','d'),('e')]

How can I do it in 1 or 2 lines of code ?

For the moment I have this:

def tuple_list(_list):
    final_list = []
    temp = []
    for idx, bat in enumerate(_list):
        temp.append(bat)
        if idx%2 == 1:
            final_list.append(temp)
            temp = []
    if len(temp) > 0: final_list.append(temp)
    return final_list
        
tuple_list(['a','b','c','d','e'])

Solution

  • You can use list comprehension. First we will have a range with a step of 2. Using this we will take proper slices from the input list to get the desired result:

    lst = ['a','b','c','d','e']
    result = [tuple(lst[i:i+2]) for i in range(0, len(lst), 2)]