Page 1 of 1

Data Structures in Python

#1 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 144
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Posted 23 January 2009 - 05:35 AM

Data Structure
A Data Structure is simply a structure which holds data together. Data structures are very useful as they are used to store a collection of of related data.

Data Structures in Python
The built-in Data Structures in Python are as follows-
1.List
2.Tuple
3.Dictionary
4.Set

List
A list is an ordered collection of data items. Lists are used to group together some other values. A list can contain values of any type. The items of a list are enclosed within square brackets. Lists are mutable, whic means you can add, remove or search for items in a list. Here is how to create a simple list-

#a list of friends is created
friends=[‘pervej’,’joy’,’arafat’]
print “I have “,len(friends),” friends. They are-“
for i in friends:
	print i
#add a new friend to friend list
friends.append(“rakib”) 
#delete an enty from friend list
del friends[1]
print “My friend list is now”,friends



Output:
I have 3 friends. They are-
pervej
joy
arafat
My friend list is now [“pervej”,”arafat”,”rakib”]

The example above demonstrates how to create a list, add & delete item from it. To access an item from a list index numbers are used. Remember, Python starts counting items in a list from 0, means first item of a list is 0,not 1.

Note: The items of a list may be of any data type. Also a list can be nested into another list. Take a look at the following lists-

list1=[6,7,8]	  #list of integers
list2=[6.3,9.0,6.1]   #list of floating points
list3=[“mango”,”apple”,”banana”]		#list of strings
list4=[“python”,12.7,25]			  #list of items of mixed data types
list5=[“apple”,8,[“atik”,”pervej”]]	   #list within another list



Tuple
Tuples are like lists except they are immutable, which means they cann’t be modified. They are usually used in cases where the collection of items need not to be changed. The items of a tuple are seperated by comma and enclosed within a pair of parentheses.

Example:Using Tuples
#creating a tuple
fruits=(“mango”,”apple”,”orange”)
new_fruits=(“banana”,”berry”,fruits)
print  fruits[1]
print  new_fruits[0]
print new_fruits[2][2]



Output:
apple
mango
orange

Tuples with print statement
Sometimes it is useful to use tuple along with print statement. Here is how it is done-

name=”atik”
age=20
print “%s is %d years of age”%(name,age)		#here (name,age) is a tuple



Output:
atik is 20 years of age

Here tuple with print statement makes it possible to avoid the usage of commas and make easy to print output. What Python does here is that it converts each item in the tuple into a string and substitutes that string value into the place of the specification.

Dictionary
Another important built-in data type in Python is dictonary. Unlike lists and tuples, dictionaries are indexed by keys whereas lists and tuples are indexed by a range of numbers. Simply a dictionary is a mapping between a set of keys and a set of values.Each key maps to a value. The association of a key-value pair is called an item. The keys are immutable.

A dictionary is defined like this: d ={key1 : value1, key2 : value2 }. The key and value pairs in a dictionary is separated by a colon, and the pairs are separated themselves by commas and all this are enclosed in a pair of curly brackets.

Take a look at the example below how to create a dictionary, add , delete and search an item-

#creating a dictionary
phone_book={“atik”:”atik.bd08@gmail.com”,
				“pervej”:”ympervej@yahoo.com”,
				“rakib”:”rakib07@yahoo.com”}
#add a new item
phone_book[“arafat”]=”aryan.ict08@yahoo.com”
#delete an existing item
del phone_book[“rakib”]
for i,j in phone_book.items():
	print “Contact %s at %s”%(i,j)
#search for an item
if phone_book.has_key(“atik”):
	print “Atik is available at %s”%”%phone_book[“atik”]



Output:
Contact atik at atik.bd08@gmail.com
Contact pervej at ympervej@yahoo.com
Contact arafat at aryan.ict08@yahoo.com
Atik is available at atik.bd08@gmail.com

Set
Newer versions of python includes a new data type named set which supports mathematical operations like union, intersection, difference and symmetric difference. A set is simply an unodered collection of elements which permits no duplicated element. So, sets are usefull in membership testing and eliminating duplicate entries.

Creating set
Sets are created using the function set() or by using curly braces. Here is how to create set-

Example:Creating set
>>>users={‘atik’,’pervej’,’rakib’,’atik’}
>>>print (users)
{‘atik’,’pervej’,’rakib’}



Here we have created a simple set named users. As i mentioned earlier, a set never permits duplicated entries. So when we print the set, we get only the unique entries. Look at the print statement, which is not similar so far we have seen. This is because at newer version of python, print() is a function and you have to print anything like this.

Set operations
We have already known that set supports mathematical operations like union, intersection, difference and symmetric difference. The following example demonstrates the mathematical operations of set-

Example:Mathematical operations of set
>>>a=set(‘abdame’)
>>>b=set(‘amtda’)
>>>a
{‘a’,’b’,’d’,’m’,’e’}
>>>b
{‘a’,’m’,’t’,’d’}
#difference of a & b
>>>a – b
{‘b’,’e’}
#union of a & b
>>>a | b
{‘a’,’b’,’d’,’m’,’e’,t’}
#intersection of a & b
>>>a & b
{‘a’,’m’,’d’}



Sequence
List, tuples and strings are example of sequences. There are two main features of sequence-
1.Indexing operation
2.Slicing operation

Indexing operation allows us to fetch a particular item in the sequence while slicing operation is useful to retrieve a slice of the sequence. The following example demonstrates these operations-

Example:Sequence operations
friends=[‘joy’,’rahat’,’rony’,’pervej’]
#indexing
print friends[0]
print friends[1]
print friends[2]
print friends[3]
print friends[-2]

#slicing using a list
print friends[1:-2]
print friends[:]

#slicing using a string
name=”atik”
print name[0:1]
print name[1:4]



Output:
joy
rahat
rony
pervej
rony
rahat
[‘joy’,’rahat’,’rony’,’pervej’]
a
tik

Is This A Good Question/Topic? 4
  • +

Replies To: Data Structures in Python

#2 desirocks  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 12-June 09

Posted 22 June 2009 - 10:53 AM

Good one mate....!!!

Keep posting more of these....... :^:

Keep :D
Was This Post Helpful? 0
  • +
  • -

#3 kebomix  Icon User is offline

  • New D.I.C Head

Reputation: 8
  • View blog
  • Posts: 3
  • Joined: 07-January 10

Posted 05 September 2010 - 09:12 AM

great post, helped me alot especially sets section
Was This Post Helpful? 0
  • +
  • -

#4 digitaldebonaire  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 23-February 13

Posted 24 February 2013 - 02:03 AM

I found this to be very informative especially how you explained a practical use for sets. keep up the good work!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1