printing contents of a list on one line

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fordie1000
    New Member
    • Mar 2008
    • 32

    printing contents of a list on one line

    Hi,

    Just wondering if someone can tell me how I could iterate through a list and
    print each item next to one another.

    for example :

    If I have a list a = [1,2,3,4,5]

    I could of course do this :

    Code:
    for item in list :
             print item
    but that prints each item on a new row .... what I want is to print each item so
    it reads like this :

    12345

    with no new line after printing each item.

    Thanks,
  • ghostdog74
    Recognized Expert Contributor
    • Apr 2006
    • 511

    #2
    try this
    print item ,

    Comment

    • jlm699
      Contributor
      • Jul 2007
      • 314

      #3
      You should try not to use list as the variable name for your lists since it is a reserved word in Python.

      Here's a tiny list comprehension that does the same thing as ghostdog's minus the spaces:
      [code=python]>>> ll = [1,2,3,4,5]
      >>> print ''.join([str(item) for item in ll])
      12345
      >>>
      [/code]
      w/o list comprehension:
      [code=python]
      >>> ll = [1,2,3,4,5]
      >>> txt = ''
      >>> for item in ll:
      ... txt += str(item)
      ...
      >>> print txt
      12345
      >>> [/code]

      Comment

      • fordie1000
        New Member
        • Mar 2008
        • 32

        #4
        Originally posted by jlm699
        You should try not to use list as the variable name for your lists since it is a reserved word in Python.

        Here's a tiny list comprehension that does the same thing as ghostdog's minus the spaces:
        [code=python]>>> ll = [1,2,3,4,5]
        >>> print ''.join([str(item) for item in ll])
        12345
        >>>
        [/code]
        w/o list comprehension:
        [code=python]
        >>> ll = [1,2,3,4,5]
        >>> txt = ''
        >>> for item in ll:
        ... txt += str(item)
        ...
        >>> print txt
        12345
        >>> [/code]
        That worked perfectly ... thanks a million.

        Comment

        • Smygis
          New Member
          • Jun 2007
          • 126

          #5
          [code=python]
          >>> li = range(10)
          >>> print reduce(lambda x, y: str(x) + str(y), li)
          0123456789
          [/code]

          ftw!

          Comment

          Working...