I have this piece of code:
def sum(L):
for x in range(len(L) //2):
a = L[x]
b = L[-x + 1]
what does these two lines of code mean:
a = L[x]
b = L[-x + 1]
I have this piece of code:
def sum(L):
for x in range(len(L) //2):
a = L[x]
b = L[-x + 1]
what does these two lines of code mean:
a = L[x]
b = L[-x + 1]
a = L[x]
Index into variable L
(like a list or a dictionary) at value x
and store that value into variable a
.
Similarly for b:
b = L[-x + 1]
This means to index into L
at value -x + 1
and store it into a variable b
.
That is some indexing. We use that to pull out a specific part of some data. my_list = [1, 2, 3, 4, 5] my_dictionary = {"element_one": 1, "element_two": 2}
This may be a little confusing, but you can call that data by indexing it, the basic of it is that this
print(my_list[0])
Will return 1. The first element will start at 0 and keep ongoing.
print(my_list[2])
That would return 3. As for the dictionary, it calls a specific value.
print(my_dictionary["element_two"])
Will return 2. If you have any questions, feel free to message me!
L[x]
is a subscription expression, useful for getting values out of lists and dictionaries, among other things.
A subscription expression is one where the first part (L
here) is an object that supports subscription. An object that supports subscription can be a built in type such as a list or dictionary. It can also be a user-defined type that has a __getitem__
method.
def sum(L):
for x in range(len(L) //2):
a = L[x]
b = L[-x + 1]
x
is a value that iterates from 0 to half the length of the list L
. So L[x]
is just going to keep walking up L
until it gets to about half way. But -x + 1
is going to be 1
, then 0
, then -1
, etc. Since lists support negative subscripts, this will get you the last half of the list, one entry at a time. (But the first two values, L[1]
and L[0]
may be bugs if you're planning to add a + b
.)
If the primary [that means
L
] is a mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. (The expression list is a tuple except if it has exactly one item.)
>>> L = {'dictionaries': 'are cool', 'and so': 'are you'}
>>> L['dictionaries']
'are cool'
If the primary is a sequence, the expression list must evaluate to an integer or a slice (as discussed in the following section).
>>> L = [1,2,3,4]
>>> L[3]
4
If you try to use subscription on an object that is not subscriptable, you'll probably get a TypeError
:
>>> 1[3]
>>> 1[3]
<stdin>:1: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
(But be careful! Strings are sequences, and therefore subscriptable!)
>>> 'hello'[3]
'l'