Can we get multiple input as tuples?

Viewed 328

I want to get multiple inputs as tuples in a list.
Example: [(1,2),(1,3),(1,4),(2,5)]
I wrote this code, it works not bad. But I'm just wondering if there is another way to do this or can we make this code clear?

def make_tuple(k):
    tup_list = []
    for i in range(0, len(k)-1, 2):
        tup_list.append((k[i],k[i+1]))
    return tup_list

list1 = list(map(int, input("Enter multiple values: ").split()))
make_tuple(list1)

In this way, user should enter the input like;
1 2 1 3 1 4 2 5 for getting [(1,2),(1,3),(1,4),(2,5)].
The actual thing I want is enter the input like;
1,2 1,3 1,4 2,5

2 Answers
import ast
a = ast.literal_eval(input('some text: '))  

input-(1,2)
output-(1,2)
input-[(1,2)]
output=[(1,2)]  

This function will accept any input that look like Python literals, such as integers, lists, dictionaries and strings
ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

you can use Zip function to achieve this.You can read more on Splitting a long tuple into smaller tuples

a = [int(char) for char in input("Enter multiple values: ")]

def zipper(iterable,n):
    args = [iter(iterable)] * n
    return zip(*args)

print(*zipper(a,2))

This way if user inputs only 5 digits it can output only 2 tuples of 2 elements each

Related