Skip to content Skip to sidebar Skip to footer

What Is " [1] ", In Sock.getsockname()[1]?

I was going through socket programming in python and I saw this : sock.getsockname()[1] , can anyone please explain what is that '[1]' for ?

Solution 1:

>>> 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

Solution 2:

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.

Solution 3:

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

Post a Comment for "What Is " [1] ", In Sock.getsockname()[1]?"