Edward Hammock
Edward Hammock

Reputation: 57

Python List and Range integration

Ok, a simple one! I have a list as follows:

SeqF = []
SeqF = range(0, 8)
SeqF[0] = [1,0,0,0]
SeqF[1] = [1,1,0,0]
SeqF[2] = [0,1,0,0]
SeqF[3] = [0,1,1,0]
SeqF[4] = [0,0,1,0]
SeqF[5] = [0,0,1,1]
SeqF[6] = [0,0,0,1]
SeqF[7] = [1,0,0,1]

Please can someone explain to me in English what this is? I get that it is a list, there is a range (0-8), but I can't get my head around it and google is getting fed up with me.

Would a more 'pythonic' way be:

SeqF = [[1,0,0,0],
        [1,1,0,0],
        [0,1,0,0],
        [0,1,1,0],
        [0,0,1,0],
        [0,0,1,1],
        [0,0,0,1],
        [1,0,0,1]]

Upvotes: 0

Views: 60

Answers (2)

thaavik
thaavik

Reputation: 3317

From the python3 docs:

Rather than being a function, range is actually an immutable sequence type

Setting items in a range like you showed is not Pythonic, and I'm surprised it actually works. (EDIT: it would only work in python2, where range returned a list)

The second option you showed is called a list literal, and is definitely the more Pythonic approach.

Upvotes: 1

Kyle Higginson
Kyle Higginson

Reputation: 942

>>> SeqF = []
>>> SeqF = range(0, 8)
>>> SeqF[0] = [1,0,0,0]
>>> SeqF[1] = [1,1,0,0]
>>> SeqF[2] = [0,1,0,0]
>>> SeqF[3] = [0,1,1,0]
>>> SeqF[4] = [0,0,1,0]
>>> SeqF[5] = [0,0,1,1]
>>> SeqF[6] = [0,0,0,1]
>>> SeqF[7] = [1,0,0,1]
>>> SeqF
[[1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [1, 0, 0, 1]]

You've produced the same thing in the bottom code in one line to that of 10 in the top line. So yes, this is definitely a more efficient and 'pythonic' way.

Upvotes: 0

Related Questions