user15124750
user15124750

Reputation:

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

Upvotes: 0

Views: 69

Answers (4)

lateBloomer
lateBloomer

Reputation: 16

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

You can slice the array by moving a sliding window of size 2 over your list.

range(start, end, step) helps you to move window by step(2 in your case) while slicing helps you create smaller list out of bigger list.

All that put into a list comprehension gives you a desired output.

Upvotes: 0

sirKJ
sirKJ

Reputation: 36

You could create an iterator with the built in iter() function and pass that to the built zip() function.

l = ['a','b','c','d','e']
i = iter(l)
zip(i, i)

if you'd like to group by 3 you can pass it 3 times to zip()

zip(i, i, i)

Upvotes: 0

forgetso
forgetso

Reputation: 2494

Try this list comprehension

x = ['a','b','c','d','e']
[(x[i],x[i+1]) for i in range(0,len(x)-1) if i%2==0]

Upvotes: 0

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21802

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

Upvotes: 1

Related Questions