1

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

trgtulas
  • 37
  • 6

2 Answers2

1
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.

zeeshan12396
  • 382
  • 1
  • 8
  • The length of the list will be more than 10 tuples. So, it would be challenging for the user to write all characters and numbers. But thanks for the commend. – trgtulas Apr 06 '22 at 12:02
0

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

logi
  • 66
  • 1
  • 1
  • 6
  • I didn't understand how I should enter the input. Could you give an example? – trgtulas Apr 06 '22 at 16:47
  • For the code above the expected input is without space like: 123456.If you want to enter input with a combination of space and comma like 1,2 3,4 5,6: then in above code replace 1st line with `a = [int(char) for char in input("Enter multiple values: ").replace(" ",",").split(",")]` – logi Apr 06 '22 at 19:02