Python Forum
"can only concatenate tuple"?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"can only concatenate tuple"?
#1
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?
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
You could also put the integer you are trying to add to the tuple into a tuple. Two tuples add and return a tuple.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to concatenate horizontally SriRajesh 2 3,407 May-23-2017, 02:00 PM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020