🐍 Python Data Structure#

πŸ‘¨β€πŸ« Vikesh K
πŸ““ Lab 02

πŸ’‘ Don’t learn and then start, start and then learn - Anon πŸ’‘

πŸ“Lab Agenda#

  • Data Structures

    • List

    • Dictionary

    • Tuples

  • Exercises

Theory#

Data Structure Summary#

data_structure_summary

Properties#

Lists#

  • Lists are also ordered sequence

  • They can be modified

  • Lists can also contain multiple data types

  • Lists can be nested

  • List elements can be accesed via an index; also negative index

  • Index can also be used to slice the lists

  • You can contcatenate lists by combining them

    • l1 = [2 , 3]

    • l2 = [5 , 6]

    • l3 = l1 + l2

  • .extend() method can be used to add elements to the list

list_elements

Tuples#

  • Tuples are ordered sequence

    • height  = (5.11, 5.5, 5.8, 5.5)

  • Different type of variables can be contained in a tuple, str, int etc.

  • The elements can be accesed via an index, staring from 0

    • negative index can also be used

  • One can concatenate tuples by adding them

    • tuple1 = (2,3,4)

    • tuple2 = tuple1 + (6,7)

  • Once created, you can’t manipulate a tuple. You will have to create a new tuple

  • Tuples can be nested. Tuples within tuples

    • nested_tuple = (1,2,("salt,"sugar"), (3,4))

Dictionary#

  • A dictionary consists of keys and values.

  • Compared to lists, instead of the numerical indexes, dictionaries have keys.

  • These keys are used to access values within a dictionary.

list_vs_dictionary

Key Functions#

Please type each of the code individually and see how it works

List Functions#

# Creating a sample list
my_list = [3, 4, 5, 6, 7, 8]

# Adding elements to the list
my_list.append(9)  # Adds 9 to the end of the list
my_list.insert(0, 2)  # Inserts 2 at index 0
my_list.extend([10, 11])  # Adds multiple elements to the end of the list

# Removing elements from the list
my_list.remove(3)  # Removes the first occurrence of 3 from the list
my_list.pop()  # Removes and returns the last element of the list
my_list.pop(2)  # Removes and returns the element at index 2

# Accessing and modifying elements in the list
my_list[0] = 1  # Replaces the element at index 0 with 1
my_list[2:4] = [0, 0]  # Replaces elements from index 2 to 4 with 0 and 0

# Sorting the list
my_list.sort()  # Sorts the list in ascending order
my_list.sort(reverse=True)  # Sorts the list in descending order
sorted_list = sorted(my_list)  # Returns a new sorted list without modifying the original list

# Other useful methods
length = len(my_list)  # Returns the number of elements in the list
count = my_list.count(5)  # Returns the number of occurrences of 5 in the list
index = my_list.index(6)  # Returns the index of the first occurrence of 6 in the list

Dictionary Functions#

# Creating a sample dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}

# Accessing and modifying dictionary items
my_dict["apple"] = 5  # Modifies the value for the key "apple"
my_dict["pear"] = 6  # Adds a new key-value pair to the dictionary
del my_dict["orange"]  # Removes the key-value pair with key "orange"

# Getting information about the dictionary
keys = my_dict.keys()  # Returns a view object of the dictionary keys
values = my_dict.values()  # Returns a view object of the dictionary values
items = my_dict.items()  # Returns a view object of the dictionary (key, value) pairs

# Other useful methods
length = len(my_dict)  # Returns the number of key-value pairs in the dictionary
exists = "pear" in my_dict  # Returns True if the key "pear" exists in the dictionary

Tuple Functions#

# Creating a sample tuple
my_tuple = (1, 2, 3, 4, 5)

# Accessing tuple elements
element = my_tuple[0]  # Returns the first element of the tuple
slice = my_tuple[1:3]  # Returns a new tuple with elements from index 1 to 3 (exclusive)

# Getting information about the tuple
length = len(my_tuple)  # Returns the number of elements in the tuple
count = my_tuple.count(3)  # Returns the number of occurrences of 3 in the tuple
index = my_tuple.index(4)  # Returns the index of the first occurrence of 4 in the tuple

Exercises#

List#

x = ["a", "b", "c"]
print(x)
['a', 'b', 'c']
# length - How many elements are in the list
# what is the type of x
# get the 3rd element of the list 

Q Extract London from the sentence

x = "London is a big city"
# x[start:stop:step]

Q What will be the result of [1,2,3] + [1,1,1]

Hint: The mathematical operations on list are very similar to how they work on string

# your code here 

Q What will be the result of x = [1,2,3] and x.extend([1,1,1])

# your code here 

You will notice that the memory location of z remains the same in the below example. This highlights the property that list are mutable

Visualise the steps on here

Q What will be the result of x = [1,2,3] and x.append([1,1,1])

# your code here 

Visualise the steps here

Q What will happen when we do z = [2,3,4]; z[0] = 5

# your code here 

Q On doing the below steps?

  • q = [1,2,3]

  • r = q

  • r[0] = 9

What will be q[0]?

# your code here 

Visualise the steps here

Q If S is a list what does the following syntax do: T = S[:]?

# your code here 

Using the [:] creates a deep copy and then s and t are not referencing to the same memory block.
Visualzise the steps here

Q Consider the following list : A = ["john",11,1.4] . What will list A contain after the following command is run: del(A[0])?

# your code here 

Q In the list L = [1,2,[3,'a'],[4,'b']]. How to extract 'b'?

# your code here 

Q What is the result of the following operation: 'P,Q,R,S'.split(',')? What will be the type of the output?

# your code here 

Tuples#

tuple1 = (2,3)
print(tuple1)
print(type(tuple1))
(2, 3)
<class 'tuple'>
tuple1[0]
2

Q What is the result of the following: len(("salt",10,1.2, "sugar",10))

# your code here 

Q Consider the tuple tuple_a = ("P","Q","R"), what is the result of the following operation tuple_a[-1]?

# your code here 

Q Consider the tuple A=((11,12),[21,22]), that contains a tuple and list. What is the result of the following operation A[1]

# your code here 

Q Consider the tuple A=((11,12),[21,22]), that contains a tuple and list. What is the result of the following operation A[0][1]?

# your code here 

Dictionary#

Its important that the key of the dictionary, is immutable. hence it can only be a number, a string or a tuple

# Create a sample dictionary
release_year_dict = { "Random_Album": ["1982","1984"],
                     "Back in Black": "1980", \
                    "The Dark Side of the Moon": "1973", 
                     "The Bodyguard": "1992", \
                    "Bat Out of Hell": "1977", 
                     "Their Greatest Hits (1971-1975)": "1976", \
                    "Saturday Night Fever": "1977", "Rumours": "1977"}
release_year_dict
{'Random_Album': ['1982', '1984'],
 'Back in Black': '1980',
 'The Dark Side of the Moon': '1973',
 'The Bodyguard': '1992',
 'Bat Out of Hell': '1977',
 'Their Greatest Hits (1971-1975)': '1976',
 'Saturday Night Fever': '1977',
 'Rumours': '1977'}
# Get all the keys in dictionary
release_year_dict.keys()
dict_keys(['Random_Album', 'Back in Black', 'The Dark Side of the Moon', 'The Bodyguard', 'Bat Out of Hell', 'Their Greatest Hits (1971-1975)', 'Saturday Night Fever', 'Rumours'])
# Get all the values in dictionary
release_year_dict.values()
dict_values([['1982', '1984'], '1980', '1973', '1992', '1977', '1976', '1977', '1977'])
release_year_dict['Back in Black']
'1980'

Add enteries to the dictionary

# Append value with key into dictionary. Add 2007 to Graduation

Delete enteries

# Delete Thriller enteries

πŸ“š Resources#

  • Python Tutor - A very good website to visualise the steps in Python. This is helpful to develop intuition behind the steps

Data Structure in Python