The zip() function in Python 3 [duplicate]

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory … Read more

How Do I Use Raw Socket in Python?

You do it like this: First you disable your network card’s automatic checksumming: sudo ethtool -K eth1 tx off And then send your dodgy frame from python 2 (You’ll have to convert to Python 3 yourself): #!/usr/bin/env python from socket import socket, AF_PACKET, SOCK_RAW s = socket(AF_PACKET, SOCK_RAW) s.bind((“eth1”, 0)) # We’re putting together an … Read more

Simulating Pointers in Python

This can be done explicitly. class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj a = ref([1, 2]) b = a print(a.get()) # => [1, 2] print(b.get()) # => [1, 2] b.set(2) print(a.get()) # => 2 print(b.get()) # => 2

Python import coding style

The (previously) top-voted answer to this question is nicely formatted but absolutely wrong about performance. Let me demonstrate Performance Top Import import random def f(): L = [] for i in xrange(1000): L.append(random.random()) for i in xrange(1000): f() $ time python import.py real 0m0.721s user 0m0.412s sys 0m0.020s Import in Function Body def f(): import … Read more

Save / load scipy sparse csr_matrix in portable data format

edit: scipy 0.19 now has scipy.sparse.save_npz and scipy.sparse.load_npz. from scipy import sparse sparse.save_npz(“yourmatrix.npz”, your_matrix) your_matrix_back = sparse.load_npz(“yourmatrix.npz”) For both functions, the file argument may also be a file-like object (i.e. the result of open) instead of a filename. Got an answer from the Scipy user group: A csr_matrix has 3 data attributes that matter: .data, … Read more