Learning Python: Programming and Data Structures- Tutorial 4- Built In Data Structures: Strings, Lists, Tuples, Dictionaries, Mutability

PYTHON

The basic built in data structures which Python provides are: Strings, Lists, Tuples and Dictionaries. 

1. Strings


In this example, we will create strings, accept strings as input, use indexing, slicing, replicating and splitting of strings.

import sys
# Demonstrating Strings in Python
# Strings are the simplest and most familiar data structures

# Here is a string constant which we will create 
greeting_statement = "Welcome to Strings in Python"

#Now, let's tell the user to enter his name
print "Can you tell us your name"
# We read the name from STDIN
# rstrip at the end is to eliminate the newline character at the end
input_name = sys.stdin.readline().rstrip()
# Now display the user a customized greeting with his name
# This will show you how strings can be concatenated
print "Demonstrating Concatenation"
print greeting_statement + "," + input_name + "!"

# Now, we will use the multiplication operator to repeat the string five times
print "Demonstrating Replication"
print greeting_statement * 5
# This will display the message Welcome to Strings in Python, five times

#Now we will demonstrate Indexing and Slicing of strings
#x[0] is the first character of the string
#x[1] is the second character of the string
#x[-1] is the last character of the string
#x[-2] is the last-but-one character of the string (or, the second-last character)
#x[1:3] will display the substring of x, from character at index 1 to character at index 3

# Demonstrate Indexes and Slicing of Strings, creating substrings

# Original greeting_statement
print "Original greeting_statement " + greeting_statement

# first character of greeting statement
print "greeting_statement[0]: (first character of greeting statement) "+greeting_statement[0]

# fourth character of greeting statement
print "greeting_statement[3]: (fourth character of greeting statement) "+greeting_statement[3]

# last character
print "greeting_statement[-1]: (last character) " + greeting_statement[-1]

# third-last character
print "greeting_statement[-3]: (third-last character) " + greeting_statement[-3]

# Displays the string from Index 1 to 4
print "greeting_statement[1:4]: (Displays the string from Index 1 to 4) " + greeting_statement[1:4]

# Displays the sub string from first character till index 2 (ie, third character)
print "greeting_statement[:2]: (Displays the string from first character till index 2 (ie, third character)::" + greeting_statement[:2]

# Displays the sub string from index =2  till the end
print "greeting_statement[:2]: (Displays the sub string from index =2  till the end)::" + greeting_statement[2:]

# Displays the length of the string
print "Length of greeting_statement :" + `len(greeting_statement)`

# Splits the string into words, by splitting the string wherever there is a space
print "Splitting the greeting_string into words using split"
print greeting_statement.split(' ')

Output of the Program:

~/work/pythontutorials$ python DataStructuresStrings.py 
Can you tell us your name
Prashant
Demonstrating Concatenation
Welcome to Strings in Python,Prashant!
Demonstrating Replication
Welcome to Strings in PythonWelcome to Strings in PythonWelcome to Strings in PythonWelcome to Strings in PythonWelcome to Strings in Python
Original greeting_statement Welcome to Strings in Python
greeting_statement[0]: (first character of greeting statement) W
greeting_statement[3]: (fourth character of greeting statement) c
greeting_statement[-1]: (last character) n
greeting_statement[-3]: (third-last character) h
greeting_statement[1:4]: (Displays the string from Index 1 to 4) elc
greeting_statement[:2]: (Displays the string from first character till index 2 (ie, third character)::We
greeting_statement[:2]: (Displays the sub string from index =2  till the end)::lcome to Strings in Python
Length of greeting_statement :28
Splitting the greeting_string into words using split
['Welcome', 'to', 'Strings', 'in', 'Python']


2. Lists


In this example, you will learn to create lists, index and slice them, append to them, delete from them, sort them and reverse them.
# Demonstrating Lists in Python 
# Lists are dynamically sized arrays. They are fairly general and can contain any linear sequence of Python objects: functions, strings, integers, floats, objects and also, other lists. It is not necessary that all objects in the list need to be of the same type. You can have a list with strings, numbers , objects; all mixed up. 

# Constructing a basic list
# This list purely has integers
test_list = [1,2,3,4,5,6,7,8,9]
print test_list

# Constructing a mixed list
# This list has integers as well as strings
test_mixed_list = [1,2,3,"test list"]
print "Displaying test_list"
print test_list    
print "Displaying test_mixed_list"
print test_mixed_list


# Appending to a list
test_list.append(10)
# Now the test_list = [1,2,3,4,5,6,7,8,9,10]
print "After appending 10 to the test_list"
print test_list
test_list = test_list + [13,12,11]
# Now the test_list = [1,2,3,4,5,6,7,8,9,10,13,12,11]
print "After adding [13,12,11] to the test list"
print test_list


# Delete from the test_list
del test_list[2]
print "Deleted element at index 2 in the test_list"
# new test list is [1,2,4,5,6,7,8,9,10,13,12,11]
print test_list

# Sorting a list
print "Sorting the test list"
test_list.sort()
print test_list
# This will display [1,2,4,5,6,7,8,9,10,11,12,13]

# Reverse a list
print "Reversting the test_list"
test_list.reverse()
print test_list
# This will display [13,12,11,10,9,8,7,6,5,4,2,1]

# Now we will demonstrate "Multiplying" a list with a constant. I.e, the 
# list will be repeatedly concatenated to itself
list_to_multiply = ['a','b','c']
print "list to multiply"
print list_to_multiply
print "After multiplying this list by 3, i.e. repeating it 3 times:"
product_list = 3 * list_to_multiply
print product_list
# This will display ['a','b','c','a','b','c','a','b','c']

Output of the program above

~/work/pythontutorials$ python DataStructuresLists.py 
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Displaying test_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Displaying test_mixed_list
[1, 2, 3, 'test list']
After appending 10 to the test_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After adding [13,12,11] to the test list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 12, 11]
Deleted element at index 2 in the test_list
[1, 2, 4, 5, 6, 7, 8, 9, 10, 13, 12, 11]
Sorting the test list
[1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Reversting the test_list
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 2, 1]
list to multiply
['a', 'b', 'c']
After multiplying this list by 3, i.e. repeating it 3 times:
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']


3. Tuples


In this example, we demonstrate how to create tuples, access values in them and create new modified tuples from them.
# Demonstrating Tuples
# Tuples are sequences of immutable Python objects. They are quite similar to lists.
# The difference is, that tuples can't be changed, once creaed. i.e. they are immutable
# Also, tuples use parentheses while Lists use Square Brackers

# Let us declare some tuples to look at the general syntax.

tuple1 = ('history','geography',1,2,3)
tuple2 = (1,10,20,30)
tuple3 = "name","age","qualification"

#Empty tuple
tuple4 = ()

# Tuple with just one element: make sure to use the comma
tuple5 = (10,)

# Accessing values in tuples. Indexing and Slicing.
# Quite similar to Lists.
print "Displaying tuple1"
print tuple1
print "Displaying tuple1[0] ..i.e, the first element of tuple1"
print tuple1[0]
# This will display: history
print "Displaying tuple1[1:3] .. i.e display a subsequence of elements of tuple1"
print tuple1[1:3]
# This will display 10, 20, 30

# Updating Tuples
# We can't update or change existing tuples since they are immutable. 
# However, we can make new tuples out of them
print "Making a new tuple from tuple2 and tuple3"
print "tuple2:"
print tuple2
print "tuple3:"
print tuple3
print "Creating a new tuple4 = tuple2 + tuple3"
tuple4 = tuple2 + tuple3
print "Tuple4:"
print tuple4
# This will print (1,10,20,30,name,age,qualification)


Output of the program above

~/work/pythontutorials$ python DataStructuresTuples.py 
Displaying tuple1
('history', 'geography', 1, 2, 3)
Displaying tuple1[0] ..i.e, the first element of tuple1
history
Displaying tuple1[1:3] .. i.e display a subsequence of elements of tuple1
('geography', 1)
Making a new tuple from tuple2 and tuple3
tuple2:
(1, 10, 20, 30)
tuple3:
('name', 'age', 'qualification')
Creating a new tuple4 = tuple2 + tuple3
Tuple4:
(1, 10, 20, 30, 'name', 'age', 'qualification')

4. Dictionaries


In this example, we show you how to create a Dictionary (HashTable), add key-value pairs to it, delete records from it, clear it and delete it.

# Python Dictionaries are Hash Tables
# Here, let us create a small telephone number directory where the Keys are the names of people
# and the values are their phone numbers

# General syntax for initializing a dictionary

phone_directory = {"Ankit":"123-56789","Alex":"567-89010","Nina":"345-678910"}

# Accessing Values in the Dictionary
print "***\nDisplaying the values in the phone directory"
print "Ankit's telephone number", phone_directory["Ankit"]
print "Alex's telephone number", phone_directory["Alex"]
print "Nina's telephone number", phone_directory["Nina"]


# Changing and Updating Values in the Dictionary
#As an example, let us change Ankit's Phone Number.
print "***\nNow, updating Ankits phone number to 321 12345"
phone_directory["Ankit"]="321-12345"
# Now let us print it
# You will notice that the phone number stored in the dictionary has changed
# And the new phone number is displayed
print phone_directory

# Removing/deleting dictionary elements
# Let's say, we'd like to remove Alex's phone number
del phone_directory["Alex"]
# Now when we print this dictionary, there will not be any record for Alex
print phone_directory

# Clearing the dictionary
phone_directory.clear()
# All recors will be wiped out from it
print phone_directory
# no key-value pairs left to display

#Deleting the dictionary
del phone_directory

#Once deleted, you can't update, access or display it


Output from the above program

~/work/pythontutorials$ python DataStructuresDictionaries.py 
***
Displaying the values in the phone directory
Ankit's telephone number 123-56789
Alex's telephone number 567-89010
Nina's telephone number 345-678910
***
Now, updating Ankits phone number to 321 12345
{'Nina': '345-678910', 'Alex': '567-89010', 'Ankit': '321-12345'}
{'Nina': '345-678910', 'Ankit': '321-12345'}
{}

5. Mutability

Lists and Dictionaries are mutable data structures. i.e, even after they have been created, you can modify them, add to them, remove elements from them.
Strings and Tuples are not mutable. You can easily create new modified Strings and Tuples but you cannot modify the original ones in place.