Double square brackets side by side in python

I am completely new in Python and have a purpose. The professor asked us to look at examples of users coding the Pascal Triangle in Python, for something that would be "similar."

I managed to find several ways to encode it, but I found that several people are using some kind of code that I do not understand.

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

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 will see that line 7 has the following:

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

I know that square brackets are lists. I know that square brackets in square brackets are lists inside / lists. Can someone describe what the square bracket does next to the square bracket?

+5
source share
2 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 can have a list in it instead of strings.

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

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

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

 l[0][1] 

l [0] gets the list first, then [1] selects the second number in it. This is why you have a square bracket next to a square bracket.

+4
source

Square brackets are used to define lists, as well as to retrieve items from lists.

When you have a list of lists and you want something from the internal list, you need to get this internal list (using brackets), and then get the right thing inside (again using brackets).

 lol = [[1, 2, 3], [4, 5, 6]] lol[1] # [4, 5, 6] lol[1][0] # 4 
+2
source

Source: https://habr.com/ru/post/1261099/


All Articles