Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double square brackets side by side in python

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?

like image 669
Syrum Avatar asked Dec 11 '16 07:12

Syrum


People also ask

What are [] used for in Python?

[] (Index brackets) Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.

How do you avoid double square brackets in Python?

How can I remove the double square brackets of a numpy array to single square brackets like a list? You could also do b = a. ravel() in this case but indexing is possibly easier. Also, be aware that some approaches will give a copy of the array whilst others will give a view.

What does double parenthesis mean in Python?

It's passing the tuple (module, item) to the function as a single argument. Without the extra parens, it would pass module and item as separate arguments.


1 Answers

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

like image 108
Bemmu Avatar answered Sep 21 '22 17:09

Bemmu