-6

I need to do: Write a function called concat_list that accepts a list of strings as an argument and returns a string made up of all elements in the list concatenated together in order. For example, if the argument is ['one', 'two', 'three'], the return value would be 'onetwothree'.

When I enter my code:

def concat_list(strings):    #idk if a list for a function has to be []
    count = ' '
    for i in strings:
        count +=1 
        return count

I get:

TypeError: cannot concatenate 'str' and 'int' objects 

on line 4. However I cannot think of another way to do this, what am I doing wrong and how do I fix it?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
tehtay
  • 35
  • 7
  • `"".join(strings)` – Andreas Oct 06 '20 at 16:41
  • 1
    [How to debug small programs.](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) | [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/843953) Your program is telling you that you're trying to add an integer (`1`) to a string (`count`), This cannot be done. – Pranav Hosangadi Oct 06 '20 at 16:42
  • 1
    A few problems with your code: Why do you `return` inside the loop? that means it will always run just one iteration. Also, what you expect will happen when you add a number to a string? Moreover, **why** do you do that? Why add 1? You want to add the strings together, maybe try `count += i`... Also try to give meaningful names. `count` is not a good name for a string (usually...) – Tomerikoo Oct 06 '20 at 16:43

2 Answers2

0

What you probably want to do is :

def concat_list(strings):
    result = "" # The constructed string
    for msg in strings:
        result += str(msg) # We had each element of the array
    return result # We return the string at the end of the loop

Or you can use :

"".join(strings)
Vinetos
  • 150
  • 1
  • 7
  • The error raised was actually nothing to do with the for loop but instead an issue with the concatenation of integers and strings. Make sure you do `result += str(msg)` so a `TypeError()` is not raised. – monsieuralfonse64 Oct 06 '20 at 16:44
0

count was defined as a string. Is this what you wanted

def concat_list(string):
   count = ""
   for i in string:
       count += i
   return count

or you can use

def concat_list(string)
    return ''.join(string)
Ekure Edem
  • 310
  • 2
  • 10