Learn List in Python

Learn List in Python

Non-Primitive Data Type

List Data Type

It behaves like a container in which we can store both types of heterogeneous and homogeneous data in a huge amount. It is a mutable data type and stored in a squared bracket []. For manipulation, it has so many methods. Now we will discuss some of the methods one by one.

let's create a list by using an inbuilt function i.e list

Input

# list is in-built function  and iterate the string one by one
l = list('python')
print(l,'\n')

print(list(range(10)))

Output

['p', 'y', 't', 'h', 'o', 'n'] 

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

let's see how to access the elements from the list

Input

# first way by using print()

lst=[[1,2,5,6,'hffhf'],True,4+2j,'sdkkj',56.4]
print(lst,'\n')

# second way by using for loop 
for i in lst:
    print(i)

Output

[[1, 2, 5, 6, 'hffhf'], True, (4+2j), 'sdkkj', 56.4] 

[1, 2, 5, 6, 'hffhf']
True
(4+2j)
sdkkj
56.4

let's see slicing and manipulation in the list by using index number

Input

# slicing the list 
l = [1,2,3,['a','b','c'],True,False,4+5j]
print(l[0])
print(l[3][2])

# manipulate the list

l[3][2] = 15
print(l)

Output

1
c
[1, 2, 3, ['a', 'b', 15], True, False, (4+5j)]

Suppose we have a list into a list and we want the sum of all the integers into a nested list so how we can find out. let's see

Input

# task -  find the sum of all integers in a nested list

lst = [[1, 2, 5, 10, 'hffhf'], True, (4+2j), 'sdkkj', 56.4]
for i in lst:
    if type(i)==list:
        print('nested list = ',i)
        n=0
        for j in i:
            if type(j)==int:
                n= n+j
        print('sum of nested list =',n)

Output

nested list =  [1, 2, 5, 10, 'hffhf']
sum of the integers in the nested list = 18

Now we'll see the inbuilt methods and functions

1. Max & Min

Input

# max and min can find only in same data type list either string or numeric
print('Max = ' , max([1,5,6,10]))

print('Min = ' , min(['d','z','a','r']))

print(min([1,5,6,10,'jhsgf']))

Output

Max =  10
Min =  a
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-9f67570e76be> in <module>
      4 print('Min = ' , min(['d','z','a','r']))
      5 
----> 6 print(min([1,5,6,10,'jhsgf']))

TypeError: '<' not supported between instances of 'str' and 'int'

2.Append

It means we can add more elements or lists into the existing list to the end of the list.

Input

#  Append does add an object or nested list to the end of the list.

lst=[45,65,4.5,154,9547]
print('original list = ',lst)
lst.append(56)
print('After append an object =' ,lst)

# append the list
lst.append(['a','b','c','d'])
print('append list into list = ',lst)

Output

original list =  [45, 65, 4.5, 154, 9547]
After append an object = [45, 65, 4.5, 154, 9547, 56]
append list into list =  [45, 65, 4.5, 154, 9547, 56, ['a', 'b', 'c', 'd']]

3. Extend

It works the same as append function but the difference is in spite of extending a list into the existing list, we have only one list.

Input

# Extend list by appending elements from the iterable.
lst1=[65,45,65.4,True,'jhds']
print('original list = ' , lst1)

# string is iterable.
lst1.extend('gh')
print('extended list = ', lst1)

lst1.extend([4,6,7,3])
print('extended list = ', lst1)

Output

original list =  [65, 45, 65.4, True, 'jhds']
extended list =  [65, 45, 65.4, True, 'jhds', 'g', 'h']
extended list =  [65, 45, 65.4, True, 'jhds', 'g', 'h', 4, 6, 7, 3]

4. Insert

We can insert only one element at a time at any index.

Input

#Insert object before index, insert only one element at a time.
lst2 = [12,15,84,6,1,0,45.1]
print('original list = ', lst2)

# insert element between 15 and 84
lst2.insert(2,95)
print('After insert the element = ', lst2)

# insert element from backward direction
lst2.insert(-2,100)
print('after insert element from back = ', lst2)

Output

original list =  [12, 15, 84, 6, 1, 0, 45.1]
After insert the element =  [12, 15, 95, 84, 6, 1, 0, 45.1]
after insert element from back =  [12, 15, 95, 84, 6, 1, 100, 0, 45.1]

5. Sort

It means to arrange the elements either in ascending or descending order. It can be applied only to the same data type(strings or numerical).

Input

#for sorting, the list must have either string or numerical data type.

lst3 = [12,1,45,94,0.4,65.7]
print('original list = ', lst3)

# by default sort in ascending order
lst3.sort()
print('sorted list(ascending) = ', lst3)

lst3.sort(reverse = True)
print('sorted list(descending) = ', lst3)

lst4 = ['d','a','c','k']
print('list = ', lst4)
lst4.sort(reverse=True)
print('sorted list = ', lst4)

Output

original list =  [12, 1, 45, 94, 0.4, 65.7]
sorted list(ascending) =  [0.4, 1, 12, 45, 65.7, 94]
sorted list(descending) =  [94, 65.7, 45, 12, 1, 0.4]
list =  ['d', 'a', 'c', 'k']
sorted list =  ['k', 'd', 'c', 'a']

6. Reverse

It just reverses the elements into the list.

Input

# reverse list
lst5 = ['rev',154,65.4,True,4+2j]
print('list = ', lst5)

lst5.reverse()
print('reversed list = ', lst5)

Output

list =  ['rev', 154, 65.4, True, (4+2j)]
reversed list =  [(4+2j), True, 65.4, 154, 'rev']

7. Count

It gives how many times particular data comes.

Input

# count function returns a number of occurrences of value.

lst6 = [4,4,5,6,7,8,10,4,5,6.5]
print('list =',lst6)

# count 4 occurrences into list
lst6.count(4)

Output

list = [4, 4, 5, 6, 7, 8, 10, 4, 5, 6.5]
3

8. Index

It gives the index number of particular data but in case of duplicate values, it returns the first index of value.

Input


lst6 = [4,4,5,6,7,8,10,4,5,6.5]
lst6.index(4)

Output

0

Remove , Pop , Clear & Copy

From the names, we can get an idea of how they work. Let's try to understand by making the programs.

Input

#Remove first occurrence of value.
lst7=[5, 6, 7, 8, 10, 5, 6.5]
lst7.remove(5)
print(lst7)

Output

[6, 7, 8, 10, 5, 6.5]

Input

#pop remove and return item at index (default last).
lst8 = [45.6,True,4+5j,'aaabb',45,65,8]
print('list = ', lst8)
lst8.pop()
#also we can remove any element using index number.
lst8.pop(5)
print('after pop list =' ,lst8)

#copy return a shallow copy of the list.
a= [45.6, True, (4+5j), 'aaabb', 45, 65, 8,'sdjfb']
b=a.copy()
print('Shallow copy = ', b)
print('a = ', a.clear())
print('still we have shallow copy of a = ' , b)

#clear remove all items from list.
lst8.clear()
print('list after clear = ', lst8)

Output

list =  [45.6, True, (4+5j), 'aaabb', 45, 65, 8]
after pop list = [45.6, True, (4+5j), 'aaabb', 45]
Shallow copy =  [45.6, True, (4+5j), 'aaabb', 45, 65, 8, 'sdjfb']
a =  None
still we have shallow copy of a =  [45.6, True, (4+5j), 'aaabb', 45, 65, 8, 'sdjfb']
list after clear =  []

For privacy purpose lists are not much safe than tuples, In the next blog, we'll learn tuples. Happy learning !!