List Methods, len function, For Loops in Python
Day 7 in #100DaysOfCode
List Methods
Python has a lot of list methods that allow us to work with lists. I have made a list here for anyone who is interested with examples:
There is also a boolean function that can be operated in this case:
numbers=[1,2,3,4,5]
print (10 in numbers)
Result:
False
Since this is a boolean function, Python will tell me if there is 10 in the list. Since 10 is not on the list, I will get the "false" result. For example, if I asked for 1, it would tell me "true"
Len Function
To know how many items there are in the list, we use the built-in function of "len". Example:
numbers=[1,2,3,4,5]
print (len(numbers))
Result:
5
For Loops
A for loop is used to iterate over a series (that is either a list, a tuple, a dictionary, a set, or a string). We declare a variable which is called "loop variable".
Here is an example: We will see each "item" in a new line.
numbers=[1,2,3,4,5]
for item in numbers:
print(item)
Result:
1
2
3
4
5
We could also achieve the same thing using the while loop but our code would be a little longer. We have to use square bracket notation and len function. It would go like this:
numbers=[1,2,3,4,5]
i = 0
while i < len(numbers):
print(numbers[i])
i=i+1
Result:
1
2
3
4
5
We achieve the same result. When compared we can say that loops is easier to implement.