Some Basic List Programs-1


List is a changeable and ordered data type that allows it to be indexed and sliced. It can contain heterogeneous values such as integers, floats, strings, tuples, lists, and dictionaries but they are commonly used to store collections of homogeneous objects.

Python program to check if a list is empty or not

  • Python treats everything as an object and objects are always true in python. However, null values, None, 0, empty data types are observed as false in python.

Python program to create a list of empty dictionaries

List comprehension is a compact method that defines a list and its contents at the same time. The basic syntax of list comprehension consists of a square bracket with an expression that is executed for each element along with for loop to iterate over each element.

Python program to find the sum of all the elements in a list

  • The sum() built-in method sums up all the numbers present in the list.

Python program to find the average of all the numbers in a list

The average of all the numbers in a list can be simply calculated by using the sum() and len() function.

  • The len() function returns the number of s in elements present in an object.

Python program to find the second largest number in a list

Python program to get a random element from a list

The random module is used to generate random numbers in python. This module implements pseudo-random number generators for various distributions.

  • The random.choice() returns a randomly selected element from a non-empty sequence.
  • The random.random() generates a random float number between 0.0 and 1.0. This random float number is then multiplied with the length of the list and typecasted to int to get an integer index value for the list.
  • The random.randrange()  generates a random number in a range specified in its argument. This generated random number is then used as an index of the list.
  • The random.randint()  generates a random integer between the specified integers. This generated random integer is then used as an index of the list.

Add Comment

%d bloggers like this: