Thursday, November 23, 2017

Python libraries and Data Structures

Python Data Structures
Following are some data structures, which are used in Python. You should be familiar with them in order to use them.

Lists – Lists are one of the most versatile data structure in Python. A list can simply be defined by writing a list of comma separated values in square brackets. Lists might contain items of different types, but usually the items all have the same type. Python lists are mutable and individual elements of a list can be changed.
Here is a quick example to define a list and then access it:
country = ["Brazil", "Russia", "India", "China", "South Africa"]
Individual elements of a list can be accessed by writing the index number in square bracket. Keep in mind that the first index of a list is 0 and not 1.
print(country[1])
#returns – Russia
A range of a script can be accessed by providing first index number and last index number.
print(country[1:3])
#returns - ['Russia', 'India']
A negative index accesses the elements of a list from end.
print(country[-2])
#returns - 'China'
A few common methods applicable to the list include: append(), extend(), insert(), remove(), count(), sort(), reverse().

Strings – Strings can simply be defined by use of single ( ‘ ), double ( ” ) or triple ( ”’ ) inverted commas. Strings enclosed in tripe quotes ( ”’ ) can span over multiple lines and are used frequently in docstrings (Python’s way of documenting functions). \ is used as an escape character. Please note that Python strings are immutable, so you cannot change part of strings.
greeting = 'Hello'
print(greeting[1])             # Returns the char of the index value 1. e
print(len(greeting))           # Prints the length of string. 5
print(greeting +' ' +'World')  # Prints Hello World.
 
Raw string can be used to pass on string as is. Python interpreter does not alter the string if you specify a string to be raw. Raw string can be defined by adding r to the string.
string = r'\n is a new line char by default.'
print(string)          # Returns - \n is a new line char by default.
Python strings are immutable and hence can't be changed.
greeting[1:] = 'i'     # Trying to change Hello to Hi. This will result an error.
 
Dictionary – Dictionary is an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
Following is a simple example –
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result –
dict['Name']:  Zara
dict['Age']:  7


No comments:

Post a Comment