List and Tuple in Python

Document
Image description

List

A list is a data type in Python used to store a collection of items. Lists are mutable, which means we can modify their contents after they are created.The data in the list is stored in the square brackets.

                        
    lst = [1,2,3,4,5]
            
        

Accessing the elements of the list

The elemnts of the list can be accessed by two methods

  • By Indexing
  • By Slice Operator

Indexing

            
    lst = [1,2,3,4]
    print(lst.[0])
    output:1              
            
        

Slice operator

        
    list = list1[start:stop:step]        
        
    

start ==>it indicates the index where slice has to startdefault value is 0
stop ===>It indicates the index where slice has to end default value is max allowed index of list ie length of the list
step ==>increment value default value is 1

        
    n=[1,2,3,4,5,6,7,8,9,10]
    print(n[2:7:2])
    print(n[4::2])
    print(n[3:7])
    print(n[8:2:-2])
     print(n[4:100])         
        
    

Tuple

Tuples are used to store multiple items in a single variable. A tuple is an immutable collection of data, meaning its elements cannot be changed once it's created. Tuples are written within parentheses.The tuple can also be defined as the read only version of the list as once the tuple is created we cannot make any changes in it.

        
    tup =(1,2,3,4,5)  
     
    

Tuple creation

  • t=() creation of empty tuple
  • t=(10,) t=10, creation of single valued tuple ,parenthesis are optional,should ends with comma
  • t=10,20,30 t=(10,20,30) creation of multi values tuples & parenthesis are optional

Accessing the elements of the Tuple

  • By Indexing
  • By Slice Operator

Indexing

        
    t=(10,20,30,40,50,60)
    print(t[0]) #10
    print(t[-1]) #60
    print(t[100]) IndexError: tuple index out of range 
        
      

Slice Operator

        
    t=(10,20,30,40,50,60)
    print(t[2:5])
    print(t[2:100])
    print(t[::2])

   Output
   (30, 40, 50)
   (30, 40, 50, 60)
   (10, 30, 50) 
        
      

Difference b/w List and tuple

List Tuple
List is a Group of Comma separated Values within Square Brackets and Square Brackets are mandatory. Tuple is a Group of Comma separated Values within Parenthesis and Parenthesis are optional.
List Objects are Mutable i.e. once we creates List Object we can perform any changes in that Object. Tuple Objeccts are Immutable i.e. once we creates Tuple Object we cannot change its content.
If the Content is not fixed and keep on changing then we should go for List. If the content is fixed and never changes then we should go for Tuple.
List Objects can not used as Keys for Dictionries because Keys should be Hashable and Immutable Tuple Objects can be used as Keys for Dictionries because Keys should be Hashable and Immutable.
Follow on LinkedIn

Comments

Popular posts from this blog

Recursion In Python

Tkinter and Api

Sets in python