Collection

In this post I will cover 4 most popular data types in python list, tuple, set, dictionary

List

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.

Usage

Most Popular Operations

Create a list a = ["a", "b", 3]
Access values in list a[1]
Updated List a[0] = 5
Delete list elements del a[1]
Reverse a list a[::-1]
Itertools [a + b for (a, b) in itertools.product(x, y)]
Select random elements in list random.choice(x) random.sample(x, 3)

Create a list

a = [1, 2, 3]
# [1, 2, 3]

Access values in list

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print list1[0]   # physics

print list2[1:5] # [2, 3, 4, 5]

Updated lists

list = ['physics', 'chemistry', 1997, 2000]
print list[2] # 1997

list[2] = 2001
print list[2] # 2001

Delete list elements

list1 = ['physics', 'chemistry', 1997, 2000];

print list1
# ['physics', 'chemistry', 1997, 2000]

del list1[2]

print list1
# ['physics', 'chemistry', 2000]

Reverse a list

[1, 3, 2][::-1]
# [2, 3, 1]

Itertools

import itertools

x = [1, 2, 3]
y = [2, 4, 5]

[a + b for (a, b) in itertools.product(x, y)]
# [3, 5, 6, 4, 6, 7, 5, 7, 8]

Select random elements in list

import random

x = [13, 23, 14, 52, 6, 23]

random.choice(x) # 52

random.sample(x, 3) # [23, 14, 52]

Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

Usage

Most Popular Operations

Create a tuple t = ("a", 1, 2)
Accessing Values in Tuples t[0], t[1:]
Updating Tuples Not allowed

Create a tuple

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
tup4 = ()
tup5 = (50, )

Accessing Values in Tuples

#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );

tup1[0]
# physics

tup2[1:5]
[2, 3, 4, 5]

Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates

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

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3

Set

Sets are lists with no duplicate entries.

The sets module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.

Usage

Most Popular Operations

Create a set x = set(["Postcard", "Radio", "Telegram"])
Add elements to a set x.add("Mobile")
Remove elements to a set x.remove("Radio")
Subset y.issubset(x)
Intersection x.intersection(y)
Difference between two sets x.difference(y)

Create a set

x = set(["Postcard", "Radio", "Telegram"])
x
# set(['Postcard', 'Telegram', 'Radio'])

Add elements to a set

x = set(["Postcard", "Radio", "Telegram"])
x.add("Mobile")
x
# set(['Postcard', 'Telegram', 'Mobile', 'Radio'])

Remove elements to a set

x = set(["Postcard", "Radio", "Telegram"])
x.remove("Radio")
x
# set(['Postcard', 'Telegram'])

Subset

x = set(["a","b","c","d"])
y = set(["c","d"])
y.issubset(x)
# True

Intersection

x = set(["a","b","c","d"])
y = set(["c","d"])
x.intersection(y)
# set(['c', 'd'])

Difference between two sets

x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
x.difference(y)
# set(['Postcard', 'Telegram'])

Dictionary

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

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.

Usage

Most Popular Operations

Create a dictionary d = {"a": 1, "b": 2, "c": 3}
Update dictionary d["a"] = 4
Delete dictionary elements del d["a"]

Create a dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

Update dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry


print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

Delete dictionary elements

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']