0

Good evening,

I am trying to make a tuple out of a list of strings. It does however not behave as expected. Can anyone enlighten me?

l = ['NP', 'shot'] 
tups = map(lambda x: tuple(x), l[-1]) 
# Desired result
print(tups) #('shot')

# Result
print(tups) #  [('s',), ('h',), ('o',), ('t',)]
# or
print(tups) # <map object at 0x000000001691FD00>

4 Answers4

2

You can simply use brackets:

l = ['NP', 'shot'] 
tups = (l[-1],)
print(tups) # ('shot')
Red
  • 26,798
  • 7
  • 36
  • 58
1

You want to be using the built in tuple() function for this

    l = ['NP', 'shot'] 
    tups = tuple(l)
    print(tups)
  • she wants ('shot') not ('NP', 'shot') – The shape Jun 06 '21 at 16:28
  • 1
    I am answering the question as asked in the title and in the text. If I googled "List of Strings to tuples in python" I would want to see the tuple() built in. – Michael Gallo Jun 06 '21 at 16:35
  • 1
    No, my answer is not wrong to the question as asked, She simply asked to convert a list of strings into a tuple. This is the list of strings, as a tuple. I am not going to count a comment as a necessary part of the question. You can give an answer to the comment , but as someone who is often very irritated with complicated answers to simple questions on SO, I am going to leave the answer that I would appreciate if I were googling the question. – Michael Gallo Jun 06 '21 at 16:46
  • look at everyone elses answer, they all give ('shot') or ('shot',) none are like yours and she stated she is asking for ('shot') your answer is wrong – The shape Jun 06 '21 at 16:48
  • and also she stated list of strings to tuple*s* and not list of strings to tuple – The shape Jun 06 '21 at 16:49
  • Everyone else can answer the comment, I'm answering the question as asked. – Michael Gallo Jun 06 '21 at 16:50
1

If, just as a thought experiment, you want map to work you would do:

>>> l = ['NP', 'shot'] 
>>> next(map(lambda x: (x,), [l[-1]]))
('shot',)

It is far better to just do:

>>> tuple([l[-1]])
('shot',)

Or use the literal tuple constructor form:

>>> (l[-1],)
('shot',)

Which can be shortened to:

>>> l[-1],
('shot',)

With tuple([l[-1]]) you need a iterable container -- in this case a list -- so that you don't get ('s', 'h', 'o', 't')

You don't need that with (l[-1],) since the arguments to the literal are not iterated; they are only evaluated:

>>> (1+2,)     #1+2 will be evaluated
(3,)

>>> ("1+2",)   # the string "1+2" is not iterated...
('1+2',)

>>> tuple(1+2)  # self explanatory error...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

>>> tuple("1+2")   # string is iterated char by char
('1', '+', '2')
dawg
  • 98,345
  • 23
  • 131
  • 206
-1

Try this:

tuple(map(str, l[-1].split(",")))

its in literal form tho

The shape
  • 359
  • 3
  • 10