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