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?
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?
>>> 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
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.
[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"