double square brackets side by side in python

Syrum picture Syrum · Dec 11, 2016 · Viewed 26.8k times · Source

I'm completely new at Python and have an assignment coming up. The professor has asked that we look at examples of users coding Pascal's Triangle in Python for something that will be 'similar'.

I managed to find several ways to code it but I found several people using some code that I don't understand.

Essentially, I'm looking to find out what it means (or does) when you see a list or variable that has two square brackets side by side. Example code:

pascalsTriangle = [[1]]
rows = int(input("Number of rows:"))
print(pascalsTriangle[0])
for i in range(1,rows+1):
    pascalsTriangle.append([1])
    for j in range(len(pascalsTriangle[i-1])-1):
        pascalsTriangle[i].append(pascalsTriangle[i-1][j]+ pascalsTriangle[i-1][j+1])
    pascalsTriangle[i].append(1)
print(pascalsTriangle[i])

You'll see that line 7 has this:

pascalsTriangle[i].append(pascalsTriangle[i-1][j]+pascalsTriangle[i-1][j+1])

I know that square brackets are lists. I know that square brackets within square brackets are lists within/of lists. Can anyone describe what a square bracket next to a square bracket is doing?

Answer

Bemmu picture Bemmu · Dec 11, 2016

If you have a list

l = ["foo", "bar", "buz"]

Then l[0] is "foo", l[1] is "bar", l[2] is buz.

Similarly you could have a list in it instead of strings.

l = [ [1,2,3], "bar", "buz"]

Now l[0] is [1,2,3].

What if you want to access the second item in that list of numbers? You could say:

l[0][1]

l[0] first gets you the list, then [1] picks out the second number in it. That's why you have "square bracket next to square bracket".