2

I have a method that takes a list of strings. Unfortunately, if the list is only one item long, Python treats this list as a string.

This post has a method for checking whether something is a string, and converting it to a list if it is: Python: How to define a function that gets a list of strings OR a string

But this seems an incredibly redundant way of getting the item that I passed in as a list to in fact be a list. Is there a better way?

Community
  • 1
  • 1
Ollyver
  • 359
  • 2
  • 14

4 Answers4

2

You are probably using tuples, not lists, and forgetting to add the comma to the one-item tuple literal(s). ('foo') is interpreted as simply 'foo' which would match what you are saying. However, adding a comma to one-item tuple literals will solve this. ('foo',) returns, well, ('foo',).

Tyler Crompton
  • 12,284
  • 14
  • 65
  • 94
1

I'm not sure I believe you, python shouldn't behave that way, and it doesn't appear to:

>>> def foo(lst):
    print type(lst)

>>> foo(['bar'])
<type 'list'>

That post was about a different thing, they wanted the ability to pass a single string or a list of strings and handle both cases as if they were lists of strings. If you're only passing in a list, always treating it as a list should be fine.

  • Thanks. As usual, having checked all my code twice before posting, turns out I was calling it in two places, and one of them was a string, not a list. *rolls eyes at self* But now I know more about how python works, so thanks everyone. – Ollyver Sep 09 '12 at 17:54
1

Python shouldn't do that with a list. A singleton tuple, though, has syntax different from singleton lists:

(1) == 1                    # (1) is 1
[1] != 1                    # [1] is a singleton list
(1,) != 1                   # (1,) is a singleton tuple
athspk
  • 6,722
  • 7
  • 37
  • 51
riamse
  • 351
  • 1
  • 4
0

You are mistaken. Python does no such transformation to lists of a single element.

Double, Triple check that you are putting the [] around the the item you are passing.

If you still can't get it working show us the code!

John La Rooy
  • 295,403
  • 53
  • 369
  • 502