0

I have built-in tuple which looks like (u,v). They are generated by Networkx and they show links in a graph. I make a list out of the called link_list.

I have to split the tuple such that the outcome would be: u , v

I tried divmod but it doesn't give the right answer.

for link in link_list:
    u,v = divmod(*link)
    print u,v
Stedy
  • 7,359
  • 14
  • 57
  • 77
masti
  • 157
  • 1
  • 5
  • 11
  • 2
    Please show an example of this "not working". – Marcin Jan 10 '12 at 15:53
  • 1
    Can you expand further on what you expect for a right answer? For example, if I gave you a tuple `(23 ,42)`, what output do you expect, and what output would your code give you currently? – Kevin Jan 10 '12 at 15:54
  • Just FYI, `divmod` returns the quotient and remainder when division is performed on its arguments. `q, r = divmod(x,y)` is equivalent to `q, r = x/y, x%y`. – chepner Jan 10 '12 at 16:25
  • The answer was simple. I was confused! – masti Jan 10 '12 at 16:32

3 Answers3

9

you can get the tuple into individual variables in the for statement as following:

for u,v in link_list:
     print u,v
Marcin
  • 48,559
  • 18
  • 128
  • 201
Aviram Segal
  • 10,962
  • 3
  • 39
  • 52
  • 3
    Alas, the shortest and most pythonic solution is the least voted. (As of now.) – Buttons840 Jan 10 '12 at 16:38
  • @Buttons840 the other nearly identical answer contained a link to the docs which is going to teach people to fish. That is probably why it was accepted instead of this answer. – istruble Jan 10 '12 at 22:38
  • @istruble Good point. That answer also received an upvote from me. – Buttons840 Jan 11 '12 at 16:58
6

Simple:

for link in link_list:
    u, v = link
    print u, v

It's called sequence unpacking.

omz
  • 53,243
  • 5
  • 129
  • 141
3

If you have a tuple (x,y), and you wish to destructure it to two variables, the syntax is simply:

u,v = (x,y)
Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 1
    I don't get it. If you already have `x` and `y`, you can just use `u,v = x,y`. If you have a tuple `link`, then you do `u,v = link`. You never need the construct you posted in your answer. – Tim Pietzcker Jan 10 '12 at 16:04
  • @TimPietzcker: imagine that the tuple `(x,y)` has been assigned to a variable, or perhaps is the return value of a function call. – Marcin Jan 10 '12 at 16:06
  • 1
    Then use that variable or the function call directly. The example you're showing is not useful. – Tim Pietzcker Jan 10 '12 at 16:09
  • @TimPietzcker: At least three other users disagree with you. – Marcin Jan 10 '12 at 16:14
  • 1
    I wouldn't make too much of it. Yesterday, eight users upvoted one of my answers which then turned out to be wrong. :) – Tim Pietzcker Jan 10 '12 at 16:21