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?
[] (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 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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With