0
def ensure_list(papers):
    if type(papers) is not list:
        papers = [papers]
    return papers

papers = 1
try:
    papers.append(7)
except:
    print "not a list"
papers = ensure_list(papers)
papers.append(5)
for item in papers:
    print item

This question is asking what is the best way to check and change a variable to a type if it is not. Is there a better way to make papers a list with the object as its first element? I am writing some code that may be given an object or a list of objects and if it is an object I want it to be appended to a list and then handled.

This is only done once so it seems like over kill to have a separate function for this.

Edit: The elements will always be a known type (custom class), and always be a list of custom type object or custom type object .

Here the answer: (Thank you Random832)

 papers if isinstance(papers, list) else [papers]

Edit2: this is not a duplicate of the other question as this is not asking how to check if something is a list. This question is asking what is the best way to check and change a variable to a type if it is not. This would apply to any type we like really, the general answer is to inline with isinstance. The answer to this specific question question is the inlined statement provided by Random832 nowhere in that other question is that listed. Please read and understand the question before you flag it.

Community
  • 1
  • 1
  • Well, you've got to decide a couple of things. What if it's a tuple? Or a generator expression? Are the elements of the list always going to be integers, or at least always of a known type? Do you really need to append more items to the list (as your `.append(5)`) or is that just an example - if you're just looping through it you can do the same with other collections. – Random832 Jul 13 '16 at 18:11
  • I'm not sure what you mean by "sleeker", though... you could inline the check as "papers if isinstance(papers, list) else [papers]", but I don't consider that "sleek" especially if you have to do it more than once. – Random832 Jul 13 '16 at 18:12
  • I believe the best thing to do is to (re)design (some of) your program so that previous functions return the type you need them to be, rather than 'ensuring' and changing types as you go along. – tenwest Jul 13 '16 at 18:28
  • Possible duplicate of [In Python, how do I determine if an object is iterable?](http://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable) – TessellatingHeckler Jul 14 '16 at 00:26

1 Answers1

0

Here it is inlined: (Thank you Random832)

 papers if isinstance(papers, list) else [papers]

The best thing to do is to (re)design (some of) your program so that previous functions return the type you need them to be. (Thank you tenwest)

Community
  • 1
  • 1