I am practicing Python. I found this below code from a website. I understood all the code except len function which holds the size of the list. I tried this code in different way, And It worked without len function. I just want to know what the use of len function here in the below code
This is the code from a website
def swapList(newList):
size = len(newList)
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
newList = [12, 35, 9, 56, 24]
print(swapList(newList))`
```
output - [24, 35, 9, 56, 12]
The above code worked fine.
This is the code that I wrote myself
temp = numbers[0]
numbers[0] = numbers[-1]
numbers[-1] = temp
return numbers
numbers = [12, 15, 18, 21, 24]
print(swapping(numbers))
output - [24, 35, 9, 56, 12]
This also works fine
len( ) function returns the size of a container, for lists it is implemented as returning number of objects within it.
Consequently x[len(x)-a]
and x[-a]
are equivalent, as long as a
is smaller or equal to len(x)
, and the two codes provided are functionally the same.
In terms of python style, the code you proposed is a more pythonic way than the one in the example you were provided.
Since the original code is a part of some "learn to python" tutorial author might prefer to be more explicit about what is going on, and thus opted for explicitly computing the length of the list. The way it is done in the tuorial example will also be more similar to how this code would look like in many other programming languages, thus for the learning purpose it might be a good choice.
As a cherry on top, the code could be further simplified to:
def swapList(x):
x[0], x[-1] = x[-1], x[0]
return x