Built in Functions of List:
all() : return True if all elements of the List are true (or if the list is empty)
>>> a = [1, 2, 0]
>>> all(a)
False
>>> a = [1, 2, 3]
>>> all(a)
True
>>> a = []
>>> all(a)
True
any() : Return True if any one of List element is True. Returns False if the List is empty.
>>> arr = [1,2,0]
>>> any(arr)
True
>>> arr = [1,2,3]
>>> any(arr)
True
>>> arr = []
>>> any(arr)
False
list():
- List is a class.
- list() is a constructor
- list() is used to construct any empty list object.
arr = list()
print("List is :", arr)
print("Length :", len(arr))
print("Any :", any(arr))
We can append elements to empty list by reading at runtime.
arr = list()
print("Initially :", arr)
print("Enter 5 elements :")
for i in range(5):
ele = input()
arr.append(ele)
print("Later :", arr)
Sum of list elements:
print("Sum of list elements")
arr = list()
n = int(input("Enter size : "))
print("Enter %d elements :" %n)
for i in range(n):
ele = int(input())
arr.append(ele)
#logic
res=0
for ele in arr:
res=res+ele
print("Sum is :", res)
max() : Returns the largest element from the List
min() : Returns minimum element from List
sorted() : Returns a new sorted list of elements (doesn’t sort the list itself)
sum() : Returns the sum of all elements in the List
>>> List = [6, 3, 8, 2, 9]
>>> min(List)
2
>>> max(List)
9
>>> sum(List)
28
>>> sorted(List)
[2, 3, 6, 8, 9]
>>> print(List)
[6, 3, 8, 2, 9]