-2

I was going through socket programming in Python and I saw this:

sock.getsockname()[1]

Can anyone please explain what is that [1] is for?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mazhar MIK
  • 1,022
  • 12
  • 14

3 Answers3

5
>>> sock.getsockname()
('0.0.0.0', 0)

The first element of the returned tuple (it is a wird kind of array) sock.getsockname()[0] is the IP, the second one sock.getsockname()[1] the port.

tuple[index] gets the object at this index in the tuple

0

sock.getsocketname() function returns array and [1] immediatelly returns you [1] of that array.

variable = sock.getsocketname()[1]

is equivalent to

arr = sock.getsocketname()
variable = arr[1]

In your case, this is socket port number.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
0

[1] is how you access to the second element of a list (first element will be [0]).

my_list = ["a", "b", "c"]
print my_list[1] # => "b"

Because sock.getsocketname() returns tuple, you access to the second element like it.

A mock showing the exact same behaviour:

def foo():
    return ("a", "b", "c")
print foo()[1] # => "b"
Arount
  • 9,853
  • 1
  • 30
  • 43