0% found this document useful (0 votes)
9 views12 pages

Week2-Python Built-In Data Structures Functions

The document outlines a lesson on Python's built-in data structures, including lists, sets, tuples, and dictionaries, aimed at BTech Computer Science students. It details the properties and uses of each data structure, along with code demonstrations for practical understanding. The instructor for the session is Dr. V. Sivakumar, and the lesson took place on January 12, 2025.

Uploaded by

Aparna Aneesh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Week2-Python Built-In Data Structures Functions

The document outlines a lesson on Python's built-in data structures, including lists, sets, tuples, and dictionaries, aimed at BTech Computer Science students. It details the properties and uses of each data structure, along with code demonstrations for practical understanding. The instructor for the session is Dr. V. Sivakumar, and the lesson took place on January 12, 2025.

Uploaded by

Aparna Aneesh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSS 1022 DATA VISUALIZATION

BTech Computer Science Stream , January 2026


Week 2 Python Buit-in Data Strucutres - Demonstration
Code

Instructor: Dr. V. Sivakumar , Date: 12/01/2025

Objective
To understand and implement Python’s fundamental built-in data structures - to create
reusable Python functions using these data structures.

Python Built-in Data Structures


Programs deal with multiple values, not just single values.
To store, organize, and process collections of data efficiently, Python provides built-
in data structures.

4 In built Data Structures in python


1. List
2. Set
3. Tuple
4. Dictionary

1. List
A list is an ordered, mutable collection of elements.

Key Properties:

Uses square brackets []


Ordered (index-based)
Heterogeneous
Allows duplicate values
Mutable (can add, remove, modify)

Why Use Lists?

When data changes frequently


Used for marks, names, dynamic data
Used for fixed records (ID, Name, Marks)
In [1]: empty_cart= []
empty_cart

Out[1]: []

In [2]: type (empty_cart)

Out[2]: list

In [3]: items_to_buy_list = ["Apple","Orange","Graphs", "Pomgranate"]


items_to_buy_list

Out[3]: ['Apple', 'Orange', 'Graphs', 'Pomgranate']

In [4]: type (items_to_buy_list)

Out[4]: list

In [5]: # Heterogeneous, Allow Duplicates


items_to_buy_list = ["Apple","Orange","Graphs","Pomgranate","Apple",5,6.7,8,10]
items_to_buy_list

Out[5]: ['Apple', 'Orange', 'Graphs', 'Pomgranate', 'Apple', 5, 6.7, 8, 10]

In [6]: type (items_to_buy_list)

Out[6]: list

In [7]: len (items_to_buy_list)

Out[7]: 9

In [8]: # Front to Back Indexing


items_to_buy_list [3]

Out[8]: 'Pomgranate'

In [9]: # Back to Front Indexing


items_to_buy_list [-4]

Out[9]: 5

In [10]: # range of data


items_to_buy_list [0:4]

Out[10]: ['Apple', 'Orange', 'Graphs', 'Pomgranate']

In [11]: # Slicing
items_to_buy_list [4:8]

Out[11]: ['Apple', 5, 6.7, 8]

In [12]: # Mutable
items_to_buy_list [2] = "Watermelon"
items_to_buy_list
Out[12]: ['Apple', 'Orange', 'Watermelon', 'Pomgranate', 'Apple', 5, 6.7, 8, 10]

In [13]: # A common use of variable unpacking is iterating over sequences of tuples or li


seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
print(f'a={a}, b={b}, c={c}')

a=1, b=2, c=3


a=4, b=5, c=6
a=7, b=8, c=9

In [14]: #Concatenating and combining lists

#Similar to tuples, adding two lists together with + concatenates them:

[4, None, "foo"] + [7, 8, (2, 3)]

Out[14]: [4, None, 'foo', 7, 8, (2, 3)]

In [15]: # Sorting
a = [7, 2, 5, 1, 3]
[Link]()

2. Set
A set is an unordered, mutable collection of unique elements.

Key Properties:

Heterogeneous
No duplicates allowed
Unordered
Supports mathematical operations (union, intersection)
No indexing → unlike lists or tuples, sets don’t support positional access like

Why Use Set?

To remove duplicates
To perform set operations efficiently

In [16]: empty_cart_2 = set ()


empty_cart_2

Out[16]: set()

In [17]: type (empty_cart_2)

Out[17]: set

In [18]: # Heterogeneous, Don't Allow Duplicates


items_to_buy_set = {"Apple","Orange","Graphs","Pomgranate","Apple",5,6.7,8,1}
items_to_buy_set

Out[18]: {1, 5, 6.7, 8, 'Apple', 'Graphs', 'Orange', 'Pomgranate'}


In [19]: type (items_to_buy_set)

Out[19]: set

In [20]: # Indexing and Slicing not Possible


items_to_buy_set[1]

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[20], line 2
1 # Indexing and Slicing not Possible
----> 2 items_to_buy_set[1]

TypeError: 'set' object is not subscriptable

In [21]: items_to_buy_set [2] = "Banana"

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[21], line 1
----> 1 items_to_buy_set [2] = "Banana"

TypeError: 'set' object does not support item assignment

In [22]: items_to_buy_set

Out[22]: {1, 5, 6.7, 8, 'Apple', 'Graphs', 'Orange', 'Pomgranate'}

In [23]: items_to_buy_set.add ("Banana")


items_to_buy_set

Out[23]: {1, 5, 6.7, 8, 'Apple', 'Banana', 'Graphs', 'Orange', 'Pomgranate'}

In [24]: items_to_buy_set.discard('Pomgranate')
items_to_buy_set

Out[24]: {1, 5, 6.7, 8, 'Apple', 'Banana', 'Graphs', 'Orange'}

[Link]
A tuple is an ordered, immutable collection of elements.

Key Properties:

Ordered (index-based)
Heterogenous
Allows duplicate values
Uses parentheses ()
Immutable (cannot be modified)

Why Use Tuples?

When data should not change


Faster than lists
Used for fixed records (ID, Name, Marks)

In [25]: empty_cart3 =()


empty_cart3

Out[25]: ()

In [26]: type (empty_cart3)

Out[26]: tuple

In [27]: tup = 1, 2, 3
tup

Out[27]: (1, 2, 3)

In [28]: # In Python, the comma defines a tuple, but parentheses are required in complex
tup = (4, 5, 6)
tup

Out[28]: (4, 5, 6)

In [29]: items_to_buy_tup = ("Apple","Orange","Graphs","Pomgranate","Apple",5,6.7,8,10)


items_to_buy_tup

Out[29]: ('Apple', 'Orange', 'Graphs', 'Pomgranate', 'Apple', 5, 6.7, 8, 10)

In [30]: type (items_to_buy_tup)

Out[30]: tuple

In [31]: items_to_buy_tup[0:3]

Out[31]: ('Apple', 'Orange', 'Graphs')

In [32]: items_to_buy_tup [2] ="Red Banana"

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[32], line 1
----> 1 items_to_buy_tup [2] ="Red Banana"

TypeError: 'tuple' object does not support item assignment

In [33]: items_to_buy_tup.count("Apple")

Out[33]: 2

In [34]: items_to_buy_tup.index("Graphs")

Out[34]: 2

In [35]: # Tuple Inside an Expression (Parentheses Required)


tup = (1 + 2, 3 + 4)
print(tup)

(3, 7)
In [36]: # Tuple of Tuples
tup = ((1, 2), (3, 4), (5, 6)) #Double Indexing
print(tup)
print(tup[1])

tup = (('a', 'b'), ('c', 'd'), (15,16))


print(tup)

print(tup[1][0]) # Access 3
print(tup[2][1]) # Access 4

((1, 2), (3, 4), (5, 6))


(3, 4)
(('a', 'b'), ('c', 'd'), (15, 16))
c
16

In [37]: # Convert a list into a tuple

tuple([4, 0, 2])

# Display the tuple data type

print(tuple)

# Convert a string into a tuple of characters


tup = tuple('string')

# Print the tuple and its type


print(tup)
print(type(tup))

<class 'tuple'>
('s', 't', 'r', 'i', 'n', 'g')
<class 'tuple'>

In [38]: tup[5]

Out[38]: 'g'

In [39]: nested_tup = (4, 5, 6), (7, 8)


nested_tup
nested_tup[0]
print (nested_tup[0])
nested_tup[1]

(4, 5, 6)
Out[39]: (7, 8)

In [40]: tup = tuple(['foo', [1, 2], True])


tup[2] = False

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[40], line 2
1 tup = tuple(['foo', [1, 2], True])
----> 2 tup[2] = False

TypeError: 'tuple' object does not support item assignment


In [41]: #If an object inside a tuple is mutable, such as a list, you can modify it in pl

tup[1].append(3)
tup

Out[41]: ('foo', [1, 2, 3], True)

In [42]: # You can concatenate tuples using the + operator to produce longer tuples:
(4, None, 'foo') + (6, 0) + ('bar',)

Out[42]: (4, None, 'foo', 6, 0, 'bar')

In [43]: # Multiplying a tuple by an integer, as with lists, has the effect of concatenat
('foo', 'bar') * 4

Out[43]: ('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')

In [44]: # Unpacking tuples

# If you try to assign to a tuple-like expression of variables, Python will atte

tup = (4, 5, 6)
a, b, c = tup
b

Out[44]: 5

In [45]: # sequences with nested tuples can be unpacked:


tup = 4, 5, (6, 7)
a, b, (c, d) = tup
c,d

Out[45]: (6, 7)

In [46]: # Swapping variables in Python

# Traditional way using a temporary variable


a = 10
b = 20
print("Before swap: a =", a, ", b =", b)

tmp = a
a = b
b = tmp
print("After traditional swap: a =", a, ", b =", b)

# Reset values
a, b = 10, 20

# Pythonic way using tuple unpacking


print("\nBefore swap: a =", a, ", b =", b)
a, b = b, a
print("After Pythonic swap: a =", a, ", b =", b)
Before swap: a = 10 , b = 20
After traditional swap: a = 20 , b = 10

Before swap: a = 10 , b = 20
After Pythonic swap: a = 20 , b = 10

In [47]: a, b = 1, 2
a
b
b, a = a, b
a
b

Out[47]: 1

[Link]
A dictionary is an unordered collection of key–value pairs.

Key Properties:

Accessed using keys, not index


Keys are unique
Values can be duplicated
Uses curly braces {}

Why Use Dictionary?

Fast data access


Used for real-world data representation (roll number → student details)

In [48]: empty_dict = {}
d1 = {"Reg No1": "Student1", "Reg No2": [1, 2, 3, 4]}
d1

Out[48]: {'Reg No1': 'Student1', 'Reg No2': [1, 2, 3, 4]}

In [49]: # You can access, insert, or set elements using the same syntax as for accessing
d1[7] = "an integer"
print (d1)

{'Reg No1': 'Student1', 'Reg No2': [1, 2, 3, 4], 7: 'an integer'}

In [50]: #You can check if a dict contains a key using the same syntax used for checking
"b" in d1

Out[50]: False

In [51]: # You can delete values either using the del keyword or the pop method (which si
d1[5] = "some value"
print (d1)
d1["dummy"] = "another value"
print (d1)
del d1[5]
print (d1)
ret = [Link]("dummy")
print (ret)
print (d1)

{'Reg No1': 'Student1', 'Reg No2': [1, 2, 3, 4], 7: 'an integer', 5: 'some valu
e'}
{'Reg No1': 'Student1', 'Reg No2': [1, 2, 3, 4], 7: 'an integer', 5: 'some valu
e', 'dummy': 'another value'}
{'Reg No1': 'Student1', 'Reg No2': [1, 2, 3, 4], 7: 'an integer', 'dummy': 'anoth
er value'}
another value
{'Reg No1': 'Student1', 'Reg No2': [1, 2, 3, 4], 7: 'an integer'}

In [52]: # The keys and values method give you iterators of the dict’s keys and values, r
# The order of the keys depends on the order of their insertion, and these funct
print (list([Link]()))
print (list([Link]()))

['Reg No1', 'Reg No2', 7]


['Student1', [1, 2, 3, 4], 'an integer']

In [53]: list([Link]())

Out[53]: [('Reg No1', 'Student1'), ('Reg No2', [1, 2, 3, 4]), (7, 'an integer')]

In [54]: # You can merge one dict into another using the update method
[Link]({"b": "foo", "c": 12})
d1

Out[54]: {'Reg No1': 'Student1',


'Reg No2': [1, 2, 3, 4],
7: 'an integer',
'b': 'foo',
'c': 12}

In [55]: # Creating dicts from sequences


# It’s common to occasionally end up with two sequences that you want to pair up
# you might write code like this:

tuples = zip(range(5), reversed(range(5)))


print (tuples)
mapping = dict(tuples)
print (mapping)

<zip object at 0x000001FFB83767C0>


{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}

In [56]: words = ["apple", "bat", "bar", "atom", "book"]


by_letter = {}

for word in words:


letter = word[0]
if letter not in by_letter:
by_letter[letter] = [word]
else:
by_letter[letter].append(word)

by_letter

Out[56]: {'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}


In [57]: by_letter = {}
for word in words:
letter = word[0]
by_letter.setdefault(letter, []).append(word)
by_letter

Out[57]: {'a': ['apple', 'atom'], 'b': ['bat', 'bar', 'book']}

In [58]: a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}

In [59]: # The union of these two sets is the set of distinct elements occurring in eithe
# This can be computed with either the union method or the | binary operator
[Link](b)
a | b

Out[59]: {1, 2, 3, 4, 5, 6, 7, 8}

In [60]: # The intersection contains the elements occurring in both sets.


# The & operator or the intersection method can be used
[Link](b)
a & b

Out[60]: {3, 4, 5}

In [61]: # All of the logical set operations have in-place counterparts, which enable you
# of the operation with the result. For very large sets, this may be more effici

c = [Link]()
c |= b # is the in-place union operator.
print (c)
d = [Link]() #Again, makes a copy of set a into d.
d &= b # is the in-place intersection operator.
d

{1, 2, 3, 4, 5, 6, 7, 8}
Out[61]: {3, 4, 5}

In [62]: # You can also check if a set is a subset of (is contained in) or a superset of
a_set = {1, 2, 3, 4, 5}
{1, 2, 3}.issubset(a_set)
a_set.issuperset({1, 2, 3})

Out[62]: True

In [63]: # Sets are equal if and only if their contents are equal
{1, 2, 3} == {3, 2, 1}

Out[63]: True

In [64]: x=sorted([7, 1, 2, 6, 0, 3, 2])


print (x)
sorted("horse race")

[0, 1, 2, 2, 3, 6, 7]
Out[64]: [' ', 'a', 'c', 'e', 'e', 'h', 'o', 'r', 'r', 's']
In [65]: seq1 = ["foo", "bar", "baz"]
seq2 = ["one", "two", "three"]
zipped = zip(seq1, seq2)
list(zipped)

Out[65]: [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]

In [66]: list(reversed(range(10)))

Out[66]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In [67]: strings = ["a", "as", "bat", "car", "dove", "python"]


[[Link]() for x in strings if len(x) > 2]

Out[67]: ['BAT', 'CAR', 'DOVE', 'PYTHON']

In [68]: all_data = [["John", "Emily", "Michael", "Mary", "Steven"],


["Maria", "Juan", "Javier", "Natalia", "Pilar"]]

In [69]: names_of_interest = []
for names in all_data:
enough_as = [name for name in names if [Link]("a") >= 2]
names_of_interest.extend(enough_as)
names_of_interest

Out[69]: ['Maria', 'Natalia']

In [70]: result = [name for names in all_data for name in names


if [Link]("a") >= 2]
result

Out[70]: ['Maria', 'Natalia']

In [71]: some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]


flattened = [x for tup in some_tuples for x in tup]
flattened

Out[71]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [77]: def my_function(x, y):


return x + y

In [78]: import re # load the regular expressions (regex) module.


def clean_strings(strings):
result = []
for value in strings:
value = [Link]() # remove leading/trailing whitespa
value = [Link]("[!#?]", "", value) # remove !, #, ?
value = [Link]() # convert to Title Case
[Link](value)
return result

# Example usage
states = [" new york!", "california#", "texas?", "florida"]
print(clean_strings(states))

['New York', 'California', 'Texas', 'Florida']


In [79]: clean_strings(states)

Out[79]: ['New York', 'California', 'Texas', 'Florida']

In [80]: import re # load the regular expressions (regex) module.

def remove_punctuation(value):
# Remove !, #, ? characters from the string
return [Link]("[!#?]", "", value)

# List of cleaning operations to apply in sequence


clean_ops = [[Link], remove_punctuation, [Link]]

def clean_strings(strings, ops):


result = []
for value in strings:
for func in ops: # Apply each function in order
value = func(value)
[Link](value) # Add cleaned string to result list
return result

# Example usage
states = [" new york!", "california#", "texas?", "florida"]
print(clean_strings(states, clean_ops))

clean_strings(states, clean_ops)

['New York', 'California', 'Texas', 'Florida']


Out[80]: ['New York', 'California', 'Texas', 'Florida']

In [81]: for x in map(remove_punctuation, states):


print(x)

new york
california
texas
florida

You might also like