Converting tuple into normal value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • parthpatel
    New Member
    • Apr 2007
    • 14

    #1

    Converting tuple into normal value

    suppose i get list of tuple as

    s = [(2,),(3,)]

    now i want to change the value of tuple to

    [2,3]

    how i can do that
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by parthpatel
    suppose i get list of tuple as

    s = [(2,),(3,)]

    now i want to change the value of tuple to

    [2,3]

    how i can do that
    Use a "list comprehension", like this:

    >>> s = [(2,),(3,)]
    >>> l = [t[0] for t in s]
    >>> l
    [2, 3]
    >>>

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by bartonc
      Use a "list comprehension", like this:

      >>> s = [(2,),(3,)]
      >>> l = [t[0] for t in s]
      >>> l
      [2, 3]
      >>>
      If you deconstruct this to a simpler (as in easier to read) form, it would look like this:
      Code:
      tupList = [(2,),(3,)]
      resultList = []
      for tup in tupList:
          resultList.append(tup[0])
      print resultList
      Once you get used to them, list comprehensions are a great tool.

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        list comprehension is the way to go. just for fun, this is an "unorthordo x" way
        Code:
        import re
        >>> map(int,re.findall("(\d+)",str(s)))
        [2, 3]

        Comment

        Working...