Sequence Type in Python


In Python sequence is the ordered collection of similer or different data types.Sequences allows to store multiple values in an organized and efficient way.

There are several sequence types in Python:-

  1. String
  2. List
  3. Tuple

1. String : In Python, strings are array of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double quote or triple quote. In Python there is no characters data type a character is a string of length one. It is represented by str class.


Example:-      string1='welcome to technical Guptaji'

                       print("string with the use of single quote:")
                       print(string1)
                       string2="It is python programming"
                       print("string with the use of double quote:")
                       string3="'Python Programming
                                                    by
                                                        Sunny Gupta"'
                       print("string with the use of triple quote:")
                       print(string3)


Accessing element of string

In Python, individual characters of a string can be accessed by using the method of indexing. Indexing start with zero index from starting. Indexing allows negative address references to access characters from the back of the string.  


Example :-  -1 refers to the last character, -2 refer to second last character and so on.

Note :  While accessing an index out of range will cause an Index Error. Only integers are allowed to be passed as an index, float or other data types will cause a Type Error.
 

The string "HELLO" is indexed as given in the below figure.

  
                         

                                                    string="HELLO"





Consider the following example : 


  1. string = "HELLO"  
  2. print(string[0])  
  3. print(string[1])  
  4. print(string[2])  
  5. print(string[3])  
  6. print(string[4])  
  7. print(string[-1])  
  8. print(string[-2])  
  9. # It returns the IndexError because 6th index doesn't exist  
  10. print(string[6])  


Output :
H
E
L
L
O
O
L
IndexError: string index out of range

        
Note : In Python, updation or deletion of characters from a string is not allowed.This will cause an error because item reassignment or item deletion from a string is not supported. This is because strings are immutable, hence elements of string can not be changed once it has been assigned. Only new string can be reassigned to the same name.









               

No comments:

Post a Comment