0

I'm working on a script where I have a list of tuples

tuple=()
number=input("Enter the how many elements you want :")
for i in range(0,number):
     ele=input("Enter the element :")
     tuple.apppend(ele)
print tuple

Append method cannot work

kaviraj
  • 60
  • 5

5 Answers5

1

You can solve it by creating your tuple-inputs from a list like so:

def GetTuple():
    data=[]
    number=input("Enter the how many elements you want :")
    for i in range(0,number):
        ele=input("Enter the element :")
        data.append(ele)

    return tuple(data)


myTup = GetTuple()
print(myTup)

If you need multiple tuples you have to call this multiple times and put each tumple inside another list. After the tuple is created, you cannot modify it.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • @kaviraj Exactly, that is the reason to collect all values stored inside that tuple into a list and converting that into a tumple at the end. The resulting tuple is immutable. If you need to mutate the values of your tuples, then you should not use them but use lists instead. – Patrick Artner Dec 28 '17 at 15:04
1

Tuples are immutable, meaning that their value cannot be changed where they're stored in memory, but rather pointing the variable to a different instance in memory.

Therefore, it does not make sense to have an append() method for an immutable type. This method is designed specifically for lists.

In your case, you might want to switch to a list rather than a tuple.

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
0

Append method cannot work

Exactly. Tuples are immutable. So provide all contents during creation. Like:

elements = tuple(input('Enter the element: ') for _ in range(number))

Demo:

>>> number = input('Enter the how many elements you want: ')
Enter the how many elements you want: 3
>>> elements = tuple(input('Enter the element: ') for _ in range(number))
Enter the element: 3.142
Enter the element: 2.718
Enter the element: 42
>>> elements
(3.142, 2.718, 42)
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0
tuple=()
number=int(input("Enter the how many elements you want :"))
for i in range(number):
    ele=input("Enter the element :")
    tuple = tuple + (int(ele),)
print(tuple)

This works on Python 3.6.

totallyhuman
  • 155
  • 1
  • 8
Alex Vask
  • 119
  • 8
0

Instead of tuple.append(ele) you could do tuple += ele,[*]. It's less efficient because it copies the whole tuple every time, but since you apparently have a person enter data manually, I assume it won't be much.

Btw, don't call it tuple. You're shadowing Python's built-in, plus you'd better use a meaningful name that describes the contents.

[*] To the inevitable noobs ignoring the comma and claiming that that doesn't work: Don't ignore the comma, and do test it.

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107