-3

I have the following python code snippet:

LL=[]
for i in range(3):
    LL.append("a"+str(i))
print LL

The output comes as:

['a0', 'a1', 'a2']

How can I print as (using print LL):

[a0, a1, a2]

i.e. without the quote mark? If I use the following code:

print "[",
for i in range (len(LL)-1):
    print LL[i] + ", ",
print LL[i+1]+"]"

This prints [a0, a1, a2]

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
  • 5
    By formatting the output. `'[{}]'.format(', '.join(LL))`. The `str()` conversion of containers is not meant for end-user use, it is a debugging tool, and not something that is meant to be configurable. – Martijn Pieters Sep 29 '15 at 16:31
  • 3
    Don't understand why I am downvoted, my basic intention is to have a clearer output, for example, say, I have a Point class having it's string representation shown as (2,3) and I would like oprint list of Points as: [(2,3), (4,5)], am I wrong in asking that? – Dr. Debasish Jana Sep 29 '15 at 16:38
  • 1
    I haven't downvoted you, but I can imagine that this was done because of the possibility to find a solution really quick over an internet search (`string formatting` or something like this as a query). I haven't downvoted your question, because it could not be clear for you, that the `'` or `"` are only indicators for the string type to distinguish if a variable is `1` (int) or `'1'` (string) for example. – colidyre Sep 29 '15 at 17:25
  • @colidyre, yes, agreed and appreciate. For printing list like [(2,3), (4,5)], presence of parentheses doesnot require another marker like a quote, right? – Dr. Debasish Jana Sep 29 '15 at 18:18
  • 2
    If the numbers are strings, the representation shows it for you with additional quotes, of course. – colidyre Sep 29 '15 at 18:21
  • @colidyre, yes, but, was looking for something without the quote, as it;s obvious when parentheses used – Dr. Debasish Jana Sep 29 '15 at 18:33
  • 2
    I cannot give you better advice than already given by Bhargav Rao – colidyre Sep 29 '15 at 19:53
  • 2
    @Dr.DebasishJana From your comments, I think you may misunderstand. The `'` only appears when the list member is a string, or another class where the `'` character is expicitly included in the `__repr__()` for the class. It is not "obvious" when parantheses are used - you only get the `'` to denote string values rather than some other sort. To use your `Point` class example - if you define `__repr__()` to not display a `'`, then it won't. This is better (less surprising) than altering the built in way that lists are displayed. See for example http://dpaste.com/2QWH266 where I implement that. – J Richard Snape Oct 02 '15 at 12:11
  • 2
    To build on Richard Snape's thought, whenever you do `print` on a list, it automatically prints `str(list)`. This `str` of list is peculiar (See [How does str(list) work?](http://stackoverflow.com/q/30109030/4099593).) It calls `repr` on each of the contents and joins them together with a `,`. Thus you get to see the `'` there as it is a side effect of `repr`. – Bhargav Rao Oct 02 '15 at 14:41

2 Answers2

12

You are printing the repr format of the list. Use join and format instead

>>> print "[{}]".format(', '.join(LL))
[a0, a1, a2]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    Is there any other way while printing the individual elements? For example, if I use as:print "[", for i in range (len(LL)-1): print LL[i] + ", ", print LL[i+1]+"]" This prints [a0, a1, a2] – Dr. Debasish Jana Sep 29 '15 at 16:43
  • 1
    @Dr.DebasishJana Not sure about what you are asking. But this is the preferred way. Yes, your technique also prints it as required but using string functions are evidently better and cleaner way of writing code. – Bhargav Rao Sep 29 '15 at 16:48
-5

Here's one utility function that worked for me:

def printList(L):
    # print list of objects using string representation
    if (len(L) == 0):
        print "[]"
        return
    s = "["
    for i in range (len(L)-1):
        s += str(L[i]) + ", "
    s += str(L[i+1]) + "]"
    print s

This works ok for list of any object, for example, if we have a point class as below:

class Point:
    def __init__(self, x_crd, y_crd):
        self.x = x_crd
        self.y = y_crd
    def __str__(self):
        return "(" + str(self.x) + "," + str(self.y) + ")"

And have a list of Point objects:

L = []
for i in range(5):
    L.append(Point(i,i))
printList(L)

And the output comes as:

[(0,0), (1,1), (2,2), (3,3), (4,4)]

And, it served my purpose. Thanks.

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
  • 3
    Concatenating strings in a loop is _very_ inefficient in Python. Remember that Python strings are immutable, so every time you add a new string to `s` in your `for` loop a new string object is allocated, the substrings are copied to it, and the old string object that was bound to `s` is destroyed. The string `.join` method (as used in Bhargav Rao's answer) operates at C speed, which is much faster than an explicit Python loop, and it can allocate a single destination string object, since it knows how large the destination needs to be, so it bypasses all that inefficiency. – PM 2Ring Sep 30 '15 at 16:04
  • @PM2Ring, please check this post, http://stackoverflow.com/questions/10043636/any-reason-not-to-use-to-concatenate-two-strings, one answer says, There is nothing wrong in concatenating two strings with +. Indeed it's easier to read than ''.join(a, b). – Dr. Debasish Jana Sep 30 '15 at 17:09
  • 4
    I agree with (most of) the information on that linked page. Concatenating two strings with `+` is perfectly ok. In fact, building a list from two strings and then calling `.join` on that list is certainly less efficient than simply using `+`. The problem is when you use `+` to build a string from several _ substrings. If the number of substrings is _guaranteed_ to be small, then go ahead and use `+`. But as the number of substrings increases using `+` becomes more & more inefficient. So doing it in a function with a loop of arbitrary size is a bad idea. – PM 2Ring Oct 01 '15 at 08:27
  • 3
    Ok. I've just run some speed tests using `timeit`. It appears that some of my information is out of date: `s += a` and `s = s + a` (where `s` and `a` are strings) have been optimized in recent versions of CPython (standard Python). So `s += a` in a loop **is** _faster_ than using `append` in a loop and then calling `.join` on the resulting list. However, using `.join` in a list comprehension is still faster than the `s += a` loop. And calling `.join` on an existing loop is even faster. However, see [this answer](http://stackoverflow.com/a/1350289/4014959) by Python developer Alex Martelli. – PM 2Ring Oct 01 '15 at 11:48