30 Days Of Python 👨‍💻 - Day 4 - Data Types III

This article is a part of a challenge series on Python. You can find the link to the previous articles in this series here:
  1. 30 Days of Python 👨‍💻 - Day One - Introduction
  2. 30 Days Of Python 👨‍💻 - Day 2 - Data Types I
  3. 30 Days of Python 👨‍💻 - Day 3 - Data Types II
As I am sharing my daily Python learning progress, it is becoming more clear and evident to me that learning and sharing explanations of concepts simultaneously helps solidify the building blocks even more. Another perk is the love from the community ❤️
 
Starting from where I left on day 3, I continued exploring about lists and the remaining data types today.
 

Actions on lists

 
Just like strings, Python provides us with some built-in methods to perform some actions on list data types. Again methods are called after the . operator on objects (here lists). The actions can be classified based on their type of actions.
Adding items to lists (append, insert, extend)
  1. scores = [44,48,55,89,34]  
  2. scores.append(100# Append adds a new item to the end  
  3. print(scores) # [44, 48, 55, 89, 34, 100]  
  4. scores.insert(034# Inserts 34 to index 0  
  5. scores.insert(244# Inserts 44 to index 2  
  6. print(scores) # [34, 44, 44, 48, 55, 89, 34, 100]  
  7. scores.extend([23]) # Extend takes an iterable (loopable items) and adds to end of list  
  8. print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23]  
  9. scores.extend([12,10])  
  10. print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23, 12, 10]  
There is a little gotcha here. These methods add items to the list in-place and do not return any value.
  1. scores = [44,48,55,89,34]  
  2. newScores = scores.append(100)  
  3. print(newScores) # None   
  4. newScores = scores.insert(0,44)  
  5. print(newScores) # None  
Removing items from list (pop, remove, clear)
  1. languages = ['C''C#''C++']  
  2. languages.pop()  
  3. print(languages) # ['C', 'C#']  
  4. languages.remove('C')  
  5. print(languages) # ['C#']  
  6. languages.clear()  
  7. print(languages) # []  
Getting index and counting (index, count)
  1. alphabets = ['a''b''c']  
  2. print(alphabets.index('a')) # 0 (Returns the index of the element in list  
  3. print(alphabets.count('b')) # 1 (counts the ocurrence of an element  
Sorting, reversing and copying lists
  1. numbers = [1,4,6,3,2,5]  
  2. numbers.sort() # Sorts the list items in place and returns nothing  
  3. print(numbers) # [1, 2, 3, 4, 5, 6] #Python also has a built in sorting function that returns a new list  
  4. sorted_numbers = sorted(numbers) # note - this is not a method  
  5. print(sorted_numbers) # [1, 2, 3, 4, 5, 6] numbers.reverse() # reverse the indices in place  
  6. print(numbers) # [6, 5, 4, 3, 2, 1] numbers_clone = numbers.copy() # another approach is numbers[:]  
  7. print(numbers_clone) # [6, 5, 4, 3, 2, 1]  
Python List methods
 

Some common list patterns

 
Finally, I explored some common patterns that are often used with lists such as reversing, which I already mentioned,  joining list into a string and cloning.
  1. avengers = ['ironman''spiderman''antman''hulk']  
  2. cloned_avengers = avengers[::1# very commonly used pattern  
  3. reversed_avengers = avengers[::-1# discussing again because it is also very common  
  4. merge_avengers = ' '.join(avengers) # used to join list into string  
  5. print(cloned_avengers) # ['ironman', 'spiderman', 'antman', 'hulk']  
  6. print(reversed_avengers) # ['hulk', 'antman', 'spiderman', 'ironman']  
  7. print(merge_avengers) # ironman spiderman antman hulk range_of_numbers = list(range[10]) # quickly generates a list of specific range  
  8. print(range_of_numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
  9. another_range = list(range(0,5)) # with start stop  
  10. print(another_range) # [0, 1, 2, 3, 4]  
List Unpacking
 
Unpacking a list is a nifty feature. It reminds me of array destructing in JavaScript which is also super cool.
  1. first,second,third = ['tesla','ford','ferarri']  
  2. print(first) # tesla  
  3. print(second) # second  
  4. print(third) # ferarri a,*others = [1,2,3,4,5] # remaining values are stored in others  
  5. print(a) # 1  
  6. print(others) # [2, 3, 4, 5] first,*others,last= [😄,😋,😠,😔,😉]  
  7. print(first) # 😄  
  8. print(others) # ['😋', '😠', '😔']  
  9. print(last) # 😉  
I hope I have been able to show some use cases for unpacking lists.
 
None
 
None is a special data type in Python which just represents the absence of value. In most other programming languages, it is commonly referred to as null
 

Dictionaries

 
A dictionary or dict is a data type in Python that contains an unorganized collection of data in a key-value pair. So dictionaries are a data structure that stores data in a specific format. In my mental model, I compared it with the JavaScript object where we store data in key-value pairs. The keys of dict are represented by strings and the values can hold any data types. The values can be accessed using the corresponding keys. Since dictionaries don’t have any order, they are scattered around in the memory, unlike lists where they are stored in order in memory.
  1. user = {'name''Max''age'40'married'False}  
  2. print(user['name']) # Max  
  3. print(user['married'# False  
Dictionary Keys
 
I mentioned that keys in a dictionary need to be of string data type. Well, that is not entirely true. dict keys can be of any immutable data type. Also, keys need to be unique. If a dictionary has more than one identical key, then the values are overridden. This is also termed as collision.
  1. abstract = { 'first'123True'hello'777: [1,3,4,5]  
  2. print(abstract['first'# 123  
  3. print(abstract[True]) # 'hello  
  4. print(abstract[777]) # [1,3,4,5] sample = { 'username': 'hisenberg', 'username': 'james'  
  5. }  
  6. print(sample['username']) # james  
Dictionary Methods
 
Checking for errors is a good programming practice because errors can break the program execution. In the context of a dictionary, if we try to access a key that does not exist, Python will throw an error and stop the program execution. This is not what we usually want so there is a built-in dictionary method to handle this.
  1. house = { 'rooms' : 4'occupants'2'doors'6  
  2. }  
  3. print(house['windows']) # KeyError: 'windows'  
  4. #instead  
  5. print(house.get('windows')) # None  
  6. print(house.get('windows'5)) # 5 (This sets a default value if no value is found)  
There are some other ways to check if a specific key or value exists in a dictionary.
  1. user = {'name''Raghav''age'20'country''India'}  
  2. print('name' in user.keys()) # True  
  3. print('gender' in user.keys()) # False  
  4. print('Raghav' in user.values()) # True  
Some other useful dictionary methods are copy, clear, pop, update.
  1. cat = { 'name''Tom''greet''meow''health'100  
  2. }  
  3. cat_copy = cat.copy()  
  4. print(cat_copy) # {'name': 'Tom', 'greet': 'meow', 'health': 100} cat.pop('name')  
  5. print(cat) # {'greet': 'meow', 'health': 100} cat.clear()  
  6. print(cat) # {} cat_copy.update({'name': 'Polo'})  
  7. print(cat_copy) # {'name': 'Polo', 'greet': 'meow', 'health': 100}  
  8. cat_copy.update({'color''Black'}) # adds key value if not present  
  9. print(cat_copy) # {'name': 'Polo', 'greet': 'meow', 'health': 100, 'color': 'Black'}  
 

Tuples

 
Tuple data type is very similar to lists but they are immutable which means their value cannot be modified nor they can be sorted like lists.
  1. my_tuple = (1,2,3# Can be any no of items  
  2. print(my_tuple[1]) # 2 (Values can be accessed just like lists)  
  3. print(1 in my_tuple) # True (Checks if element is present)  
Since tuples are immutable, they can be used as keys in dictionaries as well.
 
Actions on tuples
 
Just like lists, we can slice tuples because slicing returns a new copy and does not change the original data.
  1. colors = ('red''orange''blue''yellow')  
  2. new_colors = colors[1:4]  
  3. print(new_colors) # ('orange', 'blue', 'yellow') color_1,*others = colors # unpacking!  
  4. print(color_1) # 'red'  
  5. print(others) # ['orange', 'blue', 'yellow'] print(len(colors)) # 4  
  6. print(colors.count('red')) # 1   
  7. print(colors.index('orange')) # 1  
 

Sets

 
Finally the last of data types 😋 (unless something new pops up in the journey).
 
Sets are a data structure that stores an unordered collection of unique objects. From my JavaScript universe, I can recollect there is a Set data structure there as well so it fits my mental model.
  1. set_of_numbers = {1,2,3,4,5,5}  
  2. print(set_of_numbers) # {1,2,3,4,5} (Only unique values are stored)  
This can be very helpful to remove, say, duplicate email addresses from a list of emails.
  1. emails = ['[email protected]''[email protected]''[email protected]']  
  2. emails_set = set(emails)  
  3. unique_emails = list(emails_set)  
  4. print(unique_emails) # ['[email protected]', '[email protected]']  
Actions on sets
 
The built-in methods of sets perform actions that are exactly similar to what we learnt in Venn Diagrams in primary math class. Here are some of them. I don’t find any need to memorize them because Set is the important thing to remember. The methods can be Googled anytime.
  1. set_a = {1,2,3,4,5}  
  2. set_b = {4,5,6,7,8}  
  3. print(set_a.union(set_b)) # {1, 2, 3, 4, 5, 6, 7, 8}  
  4. print(set_a | set_b) # same as above just a compact syntax print(set_a.intersection(set_b)) # {4, 5}  
  5. print(set_a & set_b) # same as above set_a.discard(1)  
  6. print(set_a) # {2,3,4,5}  

Oh boy! We are finally done with the data for the basic building blocks of Python with a basic understanding of its data types.
 
Alt Text
 
Tomorrow the focus will be to learn the conditional flow and iterations or looping in Python. I am pumped up now. Hope you have enjoyed following along as well.
 
Have a nice one!


Similar Articles