Python Data Types

Variable data can be stored as different in memory.

What are the data types in python?

Python supports Numbers, String, List, Tuple, and Dictionary

How to declare numbers in python program?

int_variable = 100 or -100 #int - signed ineteger
long_variable = 650050001L or -650050001L #long integer
float_variable = 10.50 or -10.50 or 70.2-E12  #float
complex_variable = 5.76j or -.2456+0J  #complex numbers
a+bj # a is real part and b is imaginary part.

How to define and access strings in python program?

str_var = 'First Program!'
str_var #Complete string: First Program!
str_var[0] #first character of the string: F
str_var[2:5] #Characters starting from 3rd to 5th (index 2nd points 3rd character): rst
str_var[2:] #starts from 3rd character to last character: rst Program!
str_var * 2 #Complete string two times: First Program!First Program!
str_var + "TEST" # Concatenated string: First Program!TEST
                

del keyword

del is used to remove the variable reference.
del variable_name1 [, variable_name2, variable_name3,..]
After removed variable reference using del keyword, raises below error if we try to access that variable.
NameError: name 'var_int' is not defined

Python Example for Numbers and String Variables

#!/usr/bin/python                                                               
                                                                                
var_int = 10;                                                                   
var_float = 20.5;                                                               
var_string = "test";                                                            
                                                                                
print("integer: %d, float: %f, string: %s" % (var_int, var_float, var_string)); 
                                                                                
# del var_int                                                                   
print("integer: %d" % var_int);                                                 
                                                                                
del var_float, var_string                                                       
print("float: %f, string: %s" % (var_float, var_string));                       
Output:
$ python test_variables.py 
integer: 10, float: 20.500000, string: test
Traceback (most recent call last):
  File "test_variables.py", line 10, in 
    print("integer: %d" % var_int);
NameError: name 'var_int' is not defined

How to declare, access and update list in python?

Collection of elements and data type can be in different for each elements.
numbers_obj = [ 'one', 'two' , 'three', 'four', 'five', 'six']
numbers_obj #Complete list: ['one', 'two', 'three', 'four', 'five', 'six']
numbers_obj[0] #first element of the list: one
numbers_obj[1:4] #Starts from 2nd to 4th elements: ['two', 'three', 'four']
numbers_obj[3:] #Elements starting from 4th element: ['four', 'five', 'six']
numbers_obj * 2 #list two times: ['one', 'two', 'three', 'four', 'five', 'six', 'one', 'two', 'three', 'four', 'five', 'six']
numbers_obj+[['seven'] # combines both list: ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
 

Difference of del, remove and pop methods in python list

  • del:removes specific index element in pyhton list.
    # removes 2nd index element in list_var
    del list_var[2]; 
    
  • remove:removes first matching element in python list.
    # removes first matching element value '2' in list_var.
    list_var.remove(2); 
    
  • pop:removes specific index element and returns removed element.
    # removes 2nd index element in list_var and returns that removed 2nd index element.
    list_var.pop(2);
    

Python List Example:

#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
list_var.append('six');                                                         
                                                                                
new_list_var = ['seven', 'eight'];                                              
list_var.extend(new_list_var);                                                  
print list_var;                                                                 
                                                                                
# removes element in specific index in list                                     
del list_var[2];                                                                
print "After del 2 index in list: ";                                            
print list_var;                                                                 
                                                                                
# removes first matching element in list                                        
list_var.remove('seven');                                                       
print "After remove 'seven': ";                                                 
print list_var;                                                                 
                                                                                
# removes specific index element in list and returms removed element.           
print list_var.pop(1);                                                          
print "After pop(1): ";                                                         
print list_var;  
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']
After del 2 index in list: 
['one', 'two', 'four', 'five', 'six', 'seven', 'eight']
After remove 'seven': 
['one', 'two', 'four', 'five', 'six', 'eight']
two
After pop(1): 
['one', 'four', 'five', 'six', 'eight']

How to define and access dictionary in python?

Collection of items and each item is the combination of key and value pairs.key and value can be in different for each items.

dict_obj = {} # creates dictionary
dict_obj[key] = value #inserts or updates value for key
dict.update({'key': 'value'}) #inserts item as key and value pairs
dict.keys() #lists all keys
dict.values() #lists all values
 

Python Dictionary Example

#!/usr/bin/python                                                               
                                                                                
dict_obj = {}; # creates dictionary                                             
dict_obj['key'] = 'value'; #inserts or updates value for key                    
dict_obj.update({'key1': 'value1', 'key2': 'value2', 1:5}); #inserts item as key and value pairs
print dict_obj.items();                                                         
print dict_obj.keys(); #lists all keys                                          
print dict_obj.values(); #lists all values 
Output:
$ python test_dict.py
[('key2', 'value2'), ('key1', 'value1'), ('key', 'value'), (1, 5)]
['key2', 'key1', 'key', 1]
['value2', 'value1', 'value', 5]

How to declare, access tuples in python?

Multiple values separated by commas (',') and tuples are read-only and cannot be updated.
tuple_var = 1, 'test' # Two values 1 and 'test'
tuple_var = 1, 'test', 'three' #Three values 1, 'test' and 'three'
tuple_var[1] #Represents 2nd value 'test'
tuple_var[1:] #Represents 2nd value to last value: 'test'
tuple_var[0:2] #Represents 1st and 2nd value: 'test', 'three'
 

Python Tuples Example

#!/usr/bin/python                                                               
                                                                                
def get_tuple(name, mark1, mark2):                                              
    mark = (mark1 + mark2) / 2;                                                 
    return (name, mark);                                                        
                                                                                
var_tuple = get_tuple('student1', 78, 87);                                      
print(var_tuple[0] + " mark: " + str(var_tuple[1]));                            
Output:
$ python test_tuple.py
student1 mark: 82
if print statement concatenates string and integer value, throws below interpreter error
print(var_tuple[0] + " mark: " + var_tuple[1]);
$ python test_tuple.py
Traceback (most recent call last):
  File "test_tuple.py", line 8, in 
    print(var_tuple[0] + " mark: " + var_tuple[1]);
TypeError: cannot concatenate 'str' and 'int' objects

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^