Re: assign only first few items of a tuple/list

Discussion in 'Python' started by Terry Reedy, Dec 4, 2012.

  1. Terry Reedy

    Terry Reedy Guest

    On 12/4/2012 4:36 PM, Chris Angelico wrote:
    > On Wed, Dec 5, 2012 at 8:25 AM, Daniel Fetchinson
    > <> wrote:
    >> Hi folks, I swear I used to know this but can't find it anywhere.
    >> Say I have a list x = [ 1,2,3,4,5 ] and only care about the first two items.
    >> I'd like to assign the first two items to two variables, something like,
    >>
    >> a, b, _ = x
    >>
    >> but the above will not work, of course, but what is the common idiom
    >> for this that does?

    >
    > Try this:
    >
    > a, b, *_ = x
    >
    > Assigns 1 to a, 2 to b, and [3,4,5] to _


    Or a, b = x[0:2]; depending on whether you do or do not want the
    remainder as a separate item.

    --
    Terry Jan Reedy
     
    Terry Reedy, Dec 4, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Davy
    Replies:
    3
    Views:
    1,893
    Wildemar Wildenburger
    Nov 7, 2007
  2. Daniel Fetchinson

    assign only first few items of a tuple/list

    Daniel Fetchinson, Dec 4, 2012, in forum: Python
    Replies:
    0
    Views:
    175
    Daniel Fetchinson
    Dec 4, 2012
  3. Chris Angelico
    Replies:
    0
    Views:
    187
    Chris Angelico
    Dec 4, 2012
  4. Dave Angel
    Replies:
    0
    Views:
    200
    Dave Angel
    Dec 4, 2012
  5. Tim Chase
    Replies:
    0
    Views:
    187
    Tim Chase
    Dec 4, 2012
Loading...

Share This Page