Home > OS >  Convert list to a particular format [(123, 123), (345,875)..]
Convert list to a particular format [(123, 123), (345,875)..]

Time:04-09

I have the following list:

l = [12, 23,54, 67, 87,98,15, 90, 44,81]

I would like to convert them into pairs with parenthesis. Desired output should look like the following:

[(12, 23),(54, 67), (87,98),(15, 90), (44,81)]

What I tried so far?

print('{}'.format(' '.join('({},)'.format(i) for i in l)))

This does not print the list as pairs. How do I solve this?

CodePudding user response:

l = [12, 23,54, 67, 87,98,15, 90, 44,81]
my=[]
for i in range(0,len(l),2):
    my.append(tuple(l[i:i 2]))
print(my)

CodePudding user response:

Rather than for i in l, you'd need to use a range to allow you to set an increment by which to step through. range takes 3 arguments - a starting number, an end number, and (optionally; it defaults to 1) an increment.

Something like this:
tuple_list = [(l[i], l[i 1]) for i in range(0, len(l), 2)]

  • Related