Python3 Lists DS

Python : Data Structures


Data Structure

Lists
 
Data structure:
       A data structure is a collection of elements(such as numbers or character-or even other data structures) that is structured in some way, for example, by numbering the elements. The most basic data structure in Python is the "sequence".

->List is one of the sequence data structure
->Lists are collection of items(strings, integers or even other lists)
->Lists are enclosed within [ ]
->Each item in the list has an assigned index value.
->Each item in a list is separated by a comma( , )
->Lists are mutable, which means they can be changed.

List creation :

Eg:
       emptyList=[ ]
       lst=['one', 'two', 'three']            #list of strings
       lst2=[1,3,2,4]                           #list of integers
       lst3=[[1,2],[3,4],5,6]]              #list of lists
       lst4=[1,'krishna',4,6.5]             #list of different datatypes
       print(lst4)

output:: [1,'krishna',4,6.5]


List Length :

Eg:
       lst=['one', 'two', 'three']
       print(len(lst))               #find length of a list

output::  3

List Append :

   Syntax:

                 lst.append(x)

Eg:
       lst=['one','two','three','four']
       lst.append('five')          #append will add the item at the end
       print(lst)

output:: ['one', 'two', 'three', 'four', 'five']

List Insert

   Syntax::

                  lst.insert(x, y)

Eg:
       lst=['one', 'two', 'four']
       lst.insert(2,"three")        #will add element y at location x
       print(lst)

output::  ['one', 'two', 'three', 'four']

List Remove

   Syntax:: 

                  lst.remove(x)

Eg:
       lst=['one', 'two', 'five', 'three']
       lst.remove('five')         #remove particular element
       print(lst)

output::  ['one', 'two', 'three']

 ***   It will remove the first occurence element, if two or more same elements occur ***

List Append & Extend :

Eg: 
       lst=['one', 'two', 'three', 'four']
       lst2=['five', 'six']
       lst.append(lst2)           #append
       print(lst)

output::  ['one', 'two', 'three', 'four',['five', 'six']]

Eg:
       lst=['one', 'two', 'three', 'four']
       lst2=['five','six']
       lst.extent(lst2)     #extend will join the list with list2
       print(lst)
 
output::  ['one', 'two', 'three', 'four', 'five', 'six']

List Delete :

Eg:
      #del to remove item based on index position
       lst=['one','two','three','four','five']
   
       del lst[1]
       print(lst)

      #or we can use pop() method     
       a=lst.pop(1)
       print(a)

       print(lst)

output     ['one', 'three', 'four' ,'five]
             three
            ['one', 'four', 'five']

Eg:
       lst=['one', 'two' ,'three' ,'four']
       
      #remove an item from list
       lst.remove('three')
       print(lst)

output::  ['one' ,'two', 'four']

List realted keywords in Python :

Eg: 
      #keyword 'in' is used to test if an item is in a list
       lst=['one', 'two', 'three', 'four']

       if 'two' in list:
           print('yes')

      #keyword 'not' can combined with 'in'
       if 'six' not in lst:
           print('no')

output::   yes
                 no

List Reverse :

Eg:
      #reverse is reverses the entire list
       lst=['one', 'two', 'three', 'four']
       lst.reverse( )
       print(lst)

output:: ['four', 'three', 'two', 'one']

List Sorting :
 
          The easiest way to sort a list is with the sorted(list) function.

  That takes a list and returns a new list with those elements in sorted order.

  ** The original list is not changed.

**  The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort backwards.

Eg:
       #create a list with numbers
        nums=[3,2,5,1,4]

        sorted_lst=sorted(nums)
        print("sorted list: ",sorted_lst)
 
       #original list remains unchanged
        print("original list: ",nums)

output::    sorted list: [1,2,3,4,5]
                  original list: [3,2,5,1,4]

Eg:
       #print a list in reverse sorted order
        print("reverse sorted list: ",sorted(nums, reverse=True))

       #original list remains unchanged
        print("original list: ",nums)

output::      reverse sorted list: [5,4,3,2,1]
             original list: [3,2,5,1,4]

Sort( ) function : 

 
Eg:
       lst=[3,4,2,1,10]

       #sort the list and stored in itself
        lst.sort( )

        print("sorted list: ",lst)

output::  [1,2,3,4,10]

Eg:
       lst=[1,'a',4]
       print(lst.sort())     #sort a list elements with different datatypes.

output::  ----------------------------------------------------------------
                --
                TypeError
 
                TypeError: ' < ' not supported instances of 'str' and 'int'

List Having Multiple References :

Eg:
       lst=[1,2,3,4,5]
       abc=lst
       abc.append(6)
       print("original list: ",lst)         #print original list

output::   [1,2,3,4,5,6]

String Split to create a list :

Eg:
       #let's take a string
        a="one,two,three,four,five"
        alist=a.split(',')
        print(alist)

output::  ['one', 'two', 'three', 'four', 'five']

       s="Good to Great"
       split_list=s.split( )     #default split is white-character: space or tab
       print(split_list)

output::   ['Good' ,'to', 'Great']

List Indexing :

   Each item in the list has an assigned index value starting from 0.
   Accessing elements in a list is called indexing

Eg:
        lst=[1,2,3,4]
        print(lst[1])           #print second element
   
       #print last element using negative index
        print(lst[-1])

output::   2
                 4

 List Slicing :

        Accessing parts of segments is called slicing.
 The key point to remember is that the : end value represents the first value that is not in the selected slice.

Eg:
        nums=[10,20,30,40,50,60,70,80]
       #print all numbers
        print(nums[:])
       #print from index 0 to index 3
        print(nums[0:4])

output::   [10,20,30,40,50,60,70,80]
                 [10,20,30,40]

Eg:
       print(nums)
       print(nums[: :2])          #alternate elements in a list
       print(nums[2::2])

output:: [10,20,30,40,50,60,70,80]
               [10,30,50,70]
               [30,50,70]

List extend using "+" :

Eg:
       lst1=[1,2,3,4]
       lst2=["Ram" ,"Seeta" ,"Meena"]
       new_list=lst1+lst2
       print(new_list)

output::  [1,2,3,4,"Ram","Seeta","Meena"]

List Count :

Eg:
       nums=[1,3,4,5,4,1,5,4,3]
       print(nums.count(4))       #count the frequency of 4 in a list

output::   3
 
List Looping :

Eg: 
       #loop through a list
        lst=['one', 'two', 'three', 'four']
        for ele in lst:
              print(ele)

output::  one
                two
                three
                four

List Comprehensions :

            List comprehensions provide a concise way to create list.

  Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Eg:
       #without list comprehension
        squares=[ ]
        for i in range(10):
              squares.append(i**2)
        print(squares)

output::  [0,1,4,9,16,25,36,49,64,81]

Eg:
       #using list comprehension
        squares=[i**2 for i in range(10)]
        print(squares)

output::  [0,1,4,9,16,25,36,49,64,81]

   Eg:

       lst=[-10,-20,10,20,50]

       new_lst=[i*2 for i in lst]
       print(new_lst)

       #filter the list to exclude negative numbers
       new_lst=[i for i in lst if i>=0]
       print(new_lst)

       #create a list of tuples like (number, square_of_number)
       new_lst=[(i,i**2) for i in range(6))

output:: [-20,-40,20,40,100]
               [10,20,50]
               [(0,0),(1,1),(2,4),(3,9),(4,16),(5,25)]

Nested List Comprehensions :

       #let's suppose we have a matrix

       matrix=[
              [1,2,3,4],
              [5,6,7,8],
              [9,10,11,12]
       ]
  
       #transpose of a matrix without list comprehension
       transposed=[ ]
       for i in range(4):
             lst=[ ]
             for row in matrix:
                   lst.append(row[i])
             transposed.append(lst)

       print(transposed)

output::  [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
     

      #with list comprehension
       transposed=[[row[i] for row in matrix] for i in range(4)]
       print(transposed)

output::  [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
    


       

       

Comments

Popular posts from this blog

Python3 Function Arguments

Python3 File Handling

Python3