0

I am trying to separate some comma-separated numbers given as input:

numbers_ = input("Please enter numbers: ")
iterator_ = map(str.split(','), numbers_)
print (next(iterator_))

But I keep getting this error:

Please enter numbers: 1,2,3,4
Traceback (most recent call last):
  File "C:\Users\tomerk\PycharmProjects\pythonProject\main.py", line 3, in <module>
    print (next(iterator_))
TypeError: 'list' object is not callable

What am I doing wrong? String is an iterable object. I enter characters separated by commas without spaces.

2
  • print (iterator_) <map object at 0x000001EDB89D8400> Commented Jan 31, 2021 at 17:24
  • 2
    if you just need a list iterator, use iter(numbers_.split(',')) Commented Jan 31, 2021 at 17:34

2 Answers 2

7

You need to pass reference to function in map(). For your use case, you can use a lambda expression as:

numbers = '1,2,3,4'
iterator_ = map(lambda x: x.split(','), numbers)
print(next(iterator_))
# print: ['1'] 

Another example with external function:

def get_number(s):
    return s.split(',')

iterator_ = map(get_number, numbers)

However if you want to get numbers from the string, then you do not need map here. You need to directly use str.split() as:

>>> numbers = '1,2,3,4'
>>> numbers.split(',')
['1', '2', '3', '4']

Additionally if you want to type-cast each number from str to int type, then you can use map as:

>>> list(map(int, numbers.split(',')))
[1, 2, 3, 4]
Sign up to request clarification or add additional context in comments.

Comments

0

As the syntax is map(fun,itr). The Type Error rises in your code is for str.split(','), not for string. As str.split() returns a list which can't be used as function in map(). Instead of str.split(), you can use lambda function but carefully. You can use this code :-

numbers = input("Please enter numbers: ")
#Tt creates a list of comma seperated elements of type str
temp=numbers.split(',')
iterator_ = map(int, temp)
print(next(iterator_))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.