- 3
Why we use Len()
16 Respuestas
+ 4
len short form for length.
Example:
a = ["a", "b", "c"]
len(a) this will give the number of elements available in the list a, in this case the length of a is 3.
+ 4
Mohamed Ahmed Abdel Atty
It looks like you have forgotten a lot of python, I'll recommend to re-learn it with proper understanding and start making code using it.
+ 3
lst[i]
so when i=0, lst[0] is equal to zero index in lst which is 'a' in the lst we have.
+ 1
lst = ['a', 'b', 'c', 'g', 'i', 'a', 'a']
for i in range(len(lst)):
if lst[i] == 'a':
lst[i] = None
print(lst)
+ 1
Why we used len() here
+ 1
Mohamed Ahmed Abdel Atty
We use
for i in range(len(lst)):
because we want the index of the lst and not the element for the code logic to work because we can see that we are checking finding all the "a" in the list lst.
so we're checking
is lst[0] == 'a'?
lst[1] == 'a'?
...
lst[6] == 'a'?
So you can see that we i of for loop to be number that's we used it that way.
check this code to understand the difference -
lst = ['a', 'b', 'c', 'g', 'i', 'a', 'a']
print(len(lst),'\n') # its 7
for i in lst:
print(i)
print()
for i in range(len(lst)):
print(i)
'''
this is equivalent to because len(lst) equals 7 here
for i in range(7):
print(i)
'''
+ 1
Mohamed Ahmed Abdel Atty vertical is because of this \n
after printing each output move to next line with the help of \n
+ 1
to check if any element in lst is equal to 'a' or not.
0
It's a function that helps to know the length of the list by knowing the number of items inside it
0
Len()function is use to calculate length of the given object.
For eg consider below code
mylist=[(1,2),(3,4),(5,6)]
len(mylist)
Output=3
we get length as 4 because above list contains 3 elements
- 1
Why did you use /n in your code
- 1
And why the results are vertical
- 1
So why we used if in my code
- 1
And why we wrote lst[i]
- 1
What proper