soma
soma

Reputation: 93

Create an array{list} of sockets in python

Continuing from the question mentioned in the below link

list/array of sockets in python

Is it possible to create an array of sockets in python like

list=[socket0, socket1, socket2, socket3 ]

for i in range(0,3):
    list[i]=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    list[i].connect((host,port[0]))

I tried this but I'm getting the same error as I have posted in the link that no attribute recv.

Is it possible to create an array like this in python. I know it's possible in C.

Upvotes: 0

Views: 4949

Answers (2)

Andrey
Andrey

Reputation: 156

The fastest way:

import socket
sockets = list(map(lambda x: x.connect(('127.0.0.1', 80)), [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for _ in range(3)]))

List comprehension works faster than creation of loop with continuous append or list[i], map function does too.

More beautiful way(slightly less efficient):

import socket

not_connected_sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for _ in
    range(3)]

sockets = list(map(lambda x: x.connect(('127.0.0.1',
    80)), not_connected_sockets))

Upvotes: 0

glglgl
glglgl

Reputation: 91129

You should not pre-populate your list, but create it on the fly.

There are two way how you can do that:

  1. The "better" way:

    sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for _ in range(3)]
    for sock in sockets:
         sock.connect((host, port[0]))
    
  2. The inferior way:

    sockets = []
    for i in range(3):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port[0]))
        sockets.append(sock)
    

Despite the extra iteration, the first one is better because it uses one of Pythons "best" festures for constructing a list and is shorter and more readable. The extra iteration's timing requirements is low to non-existent.

However, there is nothing which is really against the second one, so if you prefer it although it is longer, use that.

Upvotes: 2

Related Questions