18

I've already looked at this post about iterable python errors:

"Can only iterable" Python error

But that was about the error "cannot assign an iterable". My question is why is python telling me:

 "list.py", line 6, in <module>
    reversedlist = ' '.join(toberlist1)
TypeError: can only join an iterable

I don't know what I am doing wrong! I was following this thread:

Reverse word order of a string with no str.split() allowed

and specifically this answer:

>>> s = 'This is a string to try'
>>> r = s.split(' ')
['This', 'is', 'a', 'string', 'to', 'try']
>>> r.reverse()
>>> r
['try', 'to', 'string', 'a', 'is', 'This']
>>> result = ' '.join(r)
>>> result
'try to string a is This'

and adapter the code to make it have an input. But when I ran it, it said the error above. I am a complete novice so could you please tell me what the error message means and how to fix it.

Code Below:

import re
list1 = input ("please enter the list you want to print")
print ("Your List: ", list1)
splitlist1 = list1.split(' ')
tobereversedlist1 = splitlist1.reverse()
reversedlist = ' '.join(tobereversedlist1)
yesno = input ("Press 1 for original list or 2 for reversed list")
yesnoraw = int(yesno)
if yesnoraw == 1:
    print (list1)
else:
    print (reversedlist)

The program should take an input like apples and pears and then produce an output pears and apples.

Help would be appreciated!

Community
  • 1
  • 1
Derek
  • 301
  • 2
  • 3
  • 7

3 Answers3

28

splitlist1.reverse(), like many list methods, acts in-place, and therefore returns None. So tobereversedlist1 is therefore None, hence the error.

You should pass splitlist1 directly:

splitlist1.reverse()
reversedlist = ' '.join(splitlist1)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • How would you make the program reverse lists that include commas? Like apples,pears go to pears,apples – Derek Aug 21 '15 at 15:37
  • Pass a comma to `split` instead of a space. – Daniel Roseman Aug 21 '15 at 15:39
  • How would you do both the space split and comma split at the same time? This is so yo can enter both apples,pear and apples pears regardless of the code. – Derek Aug 21 '15 at 15:41
  • There's a few ways, but probably the easiest is to replace the spaces with commas first, then split on commas: `splitlist1 = list1.replace(' ', ',').split(',')` – Daniel Roseman Aug 21 '15 at 15:43
1

string join must satisfy the connection object to be iterated(list, tuple)

splitlist1.reverse() returns None, None object not support iteration.

Eds_k
  • 944
  • 10
  • 12
0
def mostActive(customers):
    total = len(customers)
    dict_ = {}
    for i in customers:
        dict_[i] = dict_.get(i, 0) + 1
    res = {}
    for i in dict_:
        res[i] = (dict_[i]/total)*100
    print(res)
    traders = []
    for i in res:
        if res[i] >= float(5):
            traders.append(i)
    return (sorted(traders))