Python Forum

Full Version: "can only concatenate tuple"?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The question wants me to create a function that takes a tuple as an input, and returns a new tuple as an output, where every other element of the input tuple is copied, starting with the first element.
def oddTuples(aTup):
    i=0
    what_I_want=()
    while i<len(aTup):
        if i%2==0:
            final=final + aTup[i]
        i+=1
    print(what_I_want)
oddTuples((1, 2, 3, 4 ,5,))
expected output: (1, 3, 5)
actual output: typeError: can only concatenate tuple (not "int") to tuple
I'm confused about the basis of the question because I learned a tuple is immutable so how could I do this?
first of all, read this https://python-forum.io/Thread-Basic-Nev...n-sequence
it also apply to your use of while loop

there are at least three ways to do it
  • use a list, so that you can append numbers, then convert it to tuple
  • use tuple comprehension
  • use slicing to create/return copy of the tuple with desired numbers in it
You could also put the integer you are trying to add to the tuple into a tuple. Two tuples add and return a tuple.