Lists in Python | part 2

05 min read

 

List concatenation:

a= [1, 2, 3]
b= [4, 5, 6]
c = a+b
print(c)

Output:
[1, 2, 3, 4, 5, 6 ]                                    # elements in both the list are attached or concatenated.

 

'in' function:

data = [ 'book', '99', '45', 'FACE Prep'] # defined a random list 'data'
if '99' in data: # check if '99' is in 'data' , In this case the condition results "True"
data.append('100') # If '99' is present in the list append '100' at the end of the string.
print(data)

Output: [ 'book', '99', '45', 'FACE Prep', '100']

 

sort() function:

a= [10, 20, 33]
b= [14, 5, 61]
c = a+b
c.sort()
print(c)

Output:
[5, 10, 14, 20, 33 61]

Add all items in a list using sum(), to find the number of elements in a list use len(), to find the maximum in a list use max(), to find the minimum value in a list we use min(). Average of all items in a list can be found using sum()/len(). The following example would explain advanced operations on lists.

Task: Built-in functions and lists. 

nums = [3, 41, 12, 9, 24]                                # define a random list
print(len(nums)) # length of numbers
print(max(nums)) # maximum in the list
print(min(nums)) # minimum in the list
print(sums(nums)) # sum of all the elements in a list

print('Average =', sums(nums)/ len(nums)) # returns the average of all the elements

Output:

5
41
3
89
Average = 17.8
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error