Skip to main content

Python Sequence Data Types: List, tuple



In this I would like to discuss about Python data types. Usually Python don't required any variable declarations with datatype but we should aware when we are dealing with the variable values and how it stores what type of data. Let's jump into our exploration on Python data types.

Python Mutable vs Immutable datatypes


In simple way to understand this using id() function that returns address of the variables. Mutable data type means the variable stores the data at one address even different operations (+,-,/,*,%) on the variable. The content of objects of immutable types cannot be changed after they are created.
Mutable objects

  1. bytearray
  2. list
  3. set
  4. dict

Immutable objects

  • int
  • float
  • long
  • complex
  • str
  • tuple
  • frozen set

Lets test a int data type and a list data type to evaluate the immutable values with int data type while doing arthematic operation on it. Similarly list example shows how mutable type uses the same address even when an element is modified or appended with new element.
>>> x=100
>>> type(x)

>>> id(x)
161334212
>>> x=x+1
>>> id(x)
161334200
>>> l=[10,20,30]
>>> type(l)

>>> id(l)
3073114060L
>>> l[2]=50
>>> l
[10, 20, 50]
>>> type(l)

>>> id(l)
3073114060L
>>> l.append(22)
>>> l
[10, 20, 50, 22]
>>> id(l)
3073114060L

Index and Sliceing of sequences

To access the individual elements of a tuple, list, or string using square bracket [] “array” notation. Note that all these sequences index starts with 0 based.
Positive index: count from the left and move towards right, all sequences index starting with 0
>>> t=(10.4,90,888,'SysAdmin')
>>> t[0]
10.4
>>> l=['one','python',4,'admin']
>>> l[0]
'one'
>>> s='Python for Administration'
>>> s[0]
'P'
Negative index: Now the count starts from right side of sequence, this will starts with –1. Using above sequences variables to illustrate
>>> t[-1]
'SysAdmin'
>>> l[-3]
'python'
>>> s[-1]
'n'

Check sequence using in operator

Following example keep you understand about in operator which can be used in control flows such as if, while loops.
if 'python' in list1:
 print 'it is in list1'
 
if 'perl' in list2:
 print 'it is in list2'

The str object type

String is a collection of charecter set. whoes index starts with 0. we can fetch the sub set of characters from the string, where in we can use slice operations on a string with start, end index values. We can also use the skip by value as third number
s[start:end:skip]

Strings are enclosed in single or double or truple quotation marks.
var1='Hello World!'
var2='Python Programming'
print 'var1[0]: ',var1[0]
print 'var2[0:6]:',var2[0:6]
print 'Updatestring:-',var1[:6]+'Python'
print var1*2
print "My name is %s and dob is %d"%('Python',1990)
s="I'm learning Python" #  
The following are SAMPLE CODE FOR STRING METHODS out of 40 methods available for strings. Check the str functions available as standard string object offers:
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Following are the experiments with some of str methods:
# first character capitalized in string
str1='guido van rossum'
print str1.capitalize()
print str1.center(30,'*') #30 is the total width of the string,'*' is the fill char
# count substrings in orginal string 
# count() contains 3 arguments 1.substring you want to search,2.search starts of the index,3.search ending of the index
# by default start and end takes zero and len-1 respectively
sub='s';
print 'str1.count(sub,0):-',str1.count(sub,0)
sub='van'
print 'str1.count(sub):-',str1.count(sub)
str1=str1.encode('base64','strict')
print 'Encoding string :'+str1
print 'Decode string :'+str1.decode('base64','strict')
# following method returns Ture if the string endswith specified suffix
str2='Guido van Rossum'
suffix='Rossum'
print str2.endswith(suffix)
print str2.endswith(suffix,1,17)
# find string in a existed string or not
str4='Van'
print str2.find(str4)
print str2.find(str4,17)
str5='sectokphb10k'
print str5.isalnum()
str6='kumar pumps'
print str6.isalnum()
print str4.isalpha()
str7='123456789'
print str7.isdigit()
print str6.islower()
print str2.islower()
str8='   '
print str8.isspace()

The list type

When you compare with C, Java we can store similar kind of data stored as a sequence called as arrays, where as in Python we have class list base functionality is similar to array but more powerful. It can hold the heterogeneous data into them. You can add the elements at the end or in the middle or replace the existing elements. These list objects uses index that starts with 0 same as str objects.
SAMPLE CODE FOR LIST METHODS
list1=['python','CPython','jython']
list1.append('Java')
print list1
list1.insert(2,'c++')
print list1
list2=['bash','perl','shell','ruby','perl']
list1.extend(list2)
print list1
 # reversing the list
list1.reverse()
print list1

# sorting the list
list2.sort() 
print list2
# count the strings in list
value=list2.count('perl')
print value
# Locate string
index=list1.index("jython")
print index,list1[index]

The tuple type

Tuple types are immutable ordered sequence of items. These items can be of mixed types, including collection types
#!/usr/bin/python
"""
This script illustrates the usage of tuple objects
and their methods, operations
"""

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

#Concatination of tuples
tup3 = tup1 + tup2;
print tup3;

#repeating tuple
print tup1*3

#Sys admin stuff with builtin tuple here
import os
ut=os.uname()
print "uname resulted a tuple:", ut
print "Operating System:",ut[0], "\nProcessor:", ut[len(ut)-1]
It is the experiment of fetching with tuple operations +, *, in. Excution gives the output as follows:
 ~/pybin$ ./tuple1.py
(12, 34.56, 'abc', 'xyz')
(12, 34.56, 12, 34.56, 12, 34.56)
uname resulted tuple: ('Linux', 'puppet', '3.8.0-36-generic', '#52~precise1-Ubun
tu SMP Mon Feb 3 21:56:56 UTC 2014', 'i686')
Operating System: Linux
Processor: i686
We will see Sets and Dictionaries in another post soon...

Comments

Popular posts from this blog

Python Interview Questions -Coding Snipets

 This post is dedicated for all DevOps Engineer, Software Engineers who are preparing for Coding Interviews,  Overview of Coding Interviews Most Companies looking for People with minimum Coding knowledge. In a coding interview, you will be given a small problem to solve within 10 - 20 minutes online screen or in-person on their system. In the question, you might be having some part of the code framed and you might be asked to write a snippet of code in between. You need to understand the code comments and proceed to build the expected snippet of code. Bigger companies look for the General purpose questions, where small companies look for specific questions. The General questions would be like this: Determine if the given word is a palindrome or not. (Example madam) Determine given number is prime or not. How to prepare for a coding interview? Now we have the flexibility to choose the programming language on which you are comfortable.  In general DevOps Infra guys will be ...

Python Sets and Dictionaries

Python Sets Python Maps examples A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Python Set Operations and methods Python Set methods continueed >>> SET={'new','old','list','new'} >>> SET set(['new', 'old', 'list']) Lets play with set operations, it is more like school math here... >>> s={1,2,3,4} >>> k={3,4,5,6} >>> len(s) 4 >>> len(k) 4 >>> 1 in s True >>...

Program Controls and loops in Python

Python Programming controls The flow of program will be controlled with conditional statements where this flow  if condition if-else condition if-elif condition while loop while - else loop for loop for with if- else loop if condition Here I would like to work on program control statements, wherein relate some operating system functionalities so that, this would give some basic prototype for the sys admin scripts. #!/usr/bin/python # This illustrate if condition # Filename : ifex.py import os d=os.listdir('/home/pavanbsd/pybin') print d f='ifex.py' if f in d: print "File exists" else: print "Not found..." if-elif-else ladder No worries, coming soon... When you need the task that need to be done repeatedly then your choice is using loops. Python provides two simple loop constructs easy to use! More powerful then other scripting compare to, it has 'else' block. while loop Understand the power of while loop,...