Python Data Structures - Sequence types

Python has various inbuilt data structure like List, Set , Tuple, Dict which can be broadly classified in two categories.
  1. Sequence Types: The list, tuple, and str classes are sequence types in Python, representing a collection of values where order is significant. 
  2. Non- sequence types : The set, frozenset and dict classes non -sequence types in python, where order of elements is not important. 

list class: 

List is referring to each of the object being stored.
  1. The list is a referential structure which stores a sequence of references to the objects being stored. 
  2. Lists are array-based sequences and are zero-indexed.
  3. The items in a list need not be of the same type.Consider below example which indicates in a given list(list_1) are storing strings and numbers together.
    list_1 = ['physics', 'chemistry', 1997, 2000]; #String and Number both in the same list
    list_2 = [1, 2, 3, 4, 5 ];                  # Only Number in this list
    list_3 = ["a", "b", "c", "d"];    # One Character as string, Python does not have a
                                                    # separate class for characters; they are just strings with length one.
   4. Python list allows None to be present in the list. None is similar to NULL of Java.
   5. List is mutable data structure i.e:  list_1[0] = 'Math'  # first value is changed of list_1

Operations on list:-
 

List is very versatile data structure in python and it has various inbuilt methods to perform sorting , slicing, adding elements ,finding length, etc. Below we will see operation performed on list.
List creation:-
An empty list can be created as:  list = [ ]

Insert element in List: 
list.insert(<index>,<value>)
list.insert(0,"apple")
list.insert(1,"mango")
list.insert(0,"carrot")
list.insert(1,"banana")
now our modified list looks like :  ['apple', 'mango', 'carrot', 'banana']

Consider the following list  for all operations performed:
        fruits = ['apple', 'mango', 'carrot', 'banana']
  1. Find length of list : Python has inbuilt method len() to find length of list.
  2. >>> len(fruits)
    4
  3. Iteration/looping of list :  It displays each of the elements one by one as follows:
     'apple', 'mango', 'carrot', 'banana'
 for fruit in fruits: # fruits is the list to be iterated, fruit is variable pointing each of the object
     print fruit
   3. Adding an element in list using append : Python has append() method which adds object in list.
>>> fruits.append("Guava"); # Adding guava in list
>>> print fruits
['apple', 'mango', 'carrot', 'banana', 'guava']
  4.  Sorting list : python support sorting on list using sort() method.
>>> fruits.sort(); # Sorting list
>>> print fruits
['apple', 'banana', 'carrot', 'guava' ,'mango']
5. Index based access : Python's list can be accessed by index(Zero based index used). If we use negative value then it will count from end. For -1 it will give end of element of list.
>>> fruits[4] # apple is at index 0,
mango
>>> fruits[-1] # mango is at index 4 (end of list),
mango
>>> fruits[-3] # carrot is at third from last 
carrot
6. Slicing of list : Python's list can be sliced by giving< start:end> index which we want to retain(end index value is excluded).
>>>  fruits[0:3]
['apple', 'banana', 'carrot']
>>>  fruits[1:3] # No end index means go up to last
['banana', 'carrot', 'guava' ,'mango']
7. Concatenation of list  : Python's list can be added with one another.
>>> fruits = ['apple', 'banana', 'carrot', 'guava' ,'mango']
>>> fruits+=['None']
>>> fruits
['apple', 'banana', 'carrot', 'guava', 'mango', 'None']

8. List comprehension  : Python support concise way of applying an operation to a collection of objects. Iterating over an open file gives us sequence of its lines.
>>> import json
path = 'input.txt'
records = [json.loads(line) for line in open(path)]
Note :- If the data need to be stored has an identifiable structure, consider using something other than a list.

What's the difference between the list methods append() and extend()? - append vs extend 


append()- Appends object at end.
for example : fruits = ['apple', 'banana', 'carrot', 'guava' ,'mango']
fruits.append(['papaya', 'pineapple'])
print fruits
['apple', 'banana', 'carrot', 'guava' ,'mango',['papaya', 'pineapple']]

However, extend() - Eextends list by appending elements from the iterable.
in continuation of above example
fruits = ['apple', 'banana', 'carrot', 'guava' ,'mango',['papaya', 'pineapple']]
fruits.extend(['strawberry','grapes'])
print fruits
['apple', 'banana', 'carrot', 'guava' ,'mango',['papaya', 'pineapple'],'strawberry','grapes']

tuple class: 

Tuple in python is similar to list except tuple is immutable like strings i.e. you cannot modify tuples. An empty tuple can be created as follows: 
tuple_empty = ( )   #Tuples are defined by specifying items separated by commas within an optional                               # pair of parentheses. 
Lets consider following tuple :     
     animals = ('python', 'elephant', 'penguin')  
this tuple may be created without opening and closing braces like this :
     animals = 'python', 'elephant', 'penguin' 
 however, it is best practices to use opening and closing braces to indicate start and end of tuple.
1. length of tuple:  As in the list, length of tuple can be obtained using len() method.
     >>>len(animals)
     3
2. Create new tuple from existing tuple : New tuple is created from existing tuple like this :
     new_zoo = 'monkey', 'camel', animals # new_zoo tuple is created from existing tuple animals 
3. Tuple with 0 or 1 items : tuple with  0 items or empty tuple can be created as follows 
      tuple_zero_element = ( )
    tuple with 1 items needs special attention and it is created like this : 
      tuple_one_element = ( "one",)  # comma is mandatory to include in tuple with element
      Why comma is important to include ? : Because python can differentiate between a tuple and a 
      pair of parentheses surrounding the object in an expression.
4. tuple is immutable  : If we try to add(assign) or modify we get an error as follows
>>> str = (1,2,3) # tupe of 3 elements
>>> str[0]
1
>>> str[0] = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
5. Concatenation of tuple : Python's tuple can be added with another tuple. New elements are not added, new tuple is added to existing one.
>>> animals = ('python', 'elephant', 'penguin')
>>> animals += ('cow',)
>>> animals
('python', 'elephant', 'penguin', 'cow')

Question: If tuple is immutable how we can add elements new elements in it without creating new tuple ? This is a hypothetical question since why we will take immutable data structure to modify it :)
Solution: Convert tuple into list , add elements into it and again convert back to tuple. Actually, we replaced the old tuple with new one, we did not modify old tuple.
>>> elements = ('Element-1', 'Element-2', 'Element-3')
>>> elements  = list(elements)
>>> elements.insert(3, 'Element-4')
>>> elements = tuple(elements)
>>> print elements
('Element-1', 'Element-2', 'Element-3', 'Element-4')

string class:

string in python is created by enclosing immutable sequence of characters in single or double quotes. For example : 
str_1 = "SAMPLE"  or 'SAMPLE'
#python string is an indexed sequence of characters.
Indexed sequence of characters
 1.Python string support escape character in order include quote delimiter or special character as part 
     of string. Example : 'Don\' t worry' , \' is used to make ' as part of the string.
2. Unicode characters can be included, such as 20\u20AC for representing string like "20 "€ .
3.  Python also support delimiter ''' or """, to enclose multi line strings and new line character can be
     embedded naturally.
>>> print("""Welcome to the GPA calculator.
... Please enter all your letter grades, one per line.
... Enter a blank line to designate the end.""")
Welcome to the GPA calculator.
Please enter all your letter grades, one per line.
Enter a blank line to designate the end.
4. Sub-string of a string obtained using slice method.
>>> var1 = 'Hello World!'
 >>> var1[1:5]  # slice string from position 1 to 5
'ello'
5. String special operators : Consider a = 'Hello' and b =  'Python',
    'Hello' + 'python' =  'Hellopython'
     'Hello'*2 = 'HelloHello'


6. String formatting operator(%): This operator is unique to strings and it is similar to printf() function of C language. Consider the following example,%s and %d is replaced by 'Nikhil' and 2000.
>>> print "My first name is %s and salary is %d" % ('Nikhil', 2000)
My first name is Nikhil and salary is 2000
Here is the list of complete set of symbols which can be used along with %

7. Built-in string methods : Python includes the following built-in methods to manipulate strings. Here is complete list of the same. 


Previous: Python fundamentals Next: Python Data Structures - Non Sequence types

5 Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. My spouse and I love your blog and find almost all of your post’s to be just what I’m looking for. can you offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on some the subjects you write concerning here. Again, awesome weblog!
    Surya Informatics

    ReplyDelete
  3. I really appreciate your work which you have shared here about the Python Data Structures. The article you have shared here is very informative and the points you have mentioned are very helpful. Thank you so much. Data Structures and Algorithms Best Video Tutorials

    ReplyDelete
  4. Nice informative content. Thanks for sharing the valuable information.
    Node Js Development
    Node Js Framework

    ReplyDelete
Previous Post Next Post