As I am sharing my daily learning python learning progress, it is becoming more clear and evident to me that learning and sharing explaining concepts simultaneously helps solidify the building blocks even more. Another perk is the love from the community β€οΈ
Starting from where I left on day3, 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)
scores = [44,48,55,89,34]
scores.append(100) # Append adds a new item to the end
print(scores) # [44, 48, 55, 89, 34, 100]
scores.insert(0, 34) # Inserts 34 to index 0
scores.insert(2, 44) # Inserts 44 to index 2
print(scores) # [34, 44, 44, 48, 55, 89, 34, 100]
scores.extend([23]) # Extend takes an iterable (loopable items) and adds to end of list
print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23]
scores.extend([12,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.
scores = [44,48,55,89,34]
newScores = scores.append(100)
print(newScores) # None
newScores = scores.insert(0,44)
print(newScores) # None
- Removing items from list (pop, remove, clear)
languages = ['C', 'C#', 'C++']
languages.pop()
print(languages) # ['C', 'C#']
languages.remove('C')
print(languages) # ['C#']
languages.clear()
print(languages) # []
- Getting index and counting (index, count)
alphabets = ['a', 'b', 'c']
print(alphabets.index('a')) # 0 (Returns the index of the element in list
print(alphabets.count('b')) # 1 (counts the occurence of an element
- Sorting, reversing and copying lists
numbers = [1,4,6,3,2,5]
numbers.sort() # Sorts the list items in place and returns nothing
print(numbers) # [1, 2, 3, 4, 5, 6]
#Python also has a built in sorting function that returns a new list
sorted_numbers = sorted(numbers) # note - this is not a method
print(sorted_numbers) # [1, 2, 3, 4, 5, 6]
numbers.reverse() # reverse the indices in place
print(numbers) # [6, 5, 4, 3, 2, 1]
numbers_clone = numbers.copy() # another approach is numbers[:]
print(numbers_clone) # [6, 5, 4, 3, 2, 1]
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
avengers = ['ironman', 'spiderman', 'antman', 'hulk']
cloned_avengers = avengers[::1] # very commonly used pattern
reversed_avengers = avengers[::-1] # discussing again because it is also very common
merge_avengers = ' '.join(avengers) # used to join list into string
print(cloned_avengers) # ['ironman', 'spiderman', 'antman', 'hulk']
print(reversed_avengers) # ['hulk', 'antman', 'spiderman', 'ironman']
print(merge_avengers) # ironman spiderman antman hulk
range_of_numbers = list(range(10)) # quickly generates a list of specific range
print(range_of_numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
another_range = list(range(0,5)) # with start stop
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.
first,second,third = ['tesla','ford','ferarri']
print(first) # tesla
print(second) # second
print(third) # ferarri
a,*others = [1,2,3,4,5] # remaining values are stored in others
print(a) # 1
print(others) # [2, 3, 4, 5]
first,*others,last= [π,π,π ,π,π]
print(first) # π
print(others) # ['π', 'π ', 'π']
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.
user = {'name': 'Max', 'age': 40, 'married': False}
print(user['name']) # Max
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.
abstract = {
'first': 123,
True: 'hello',
777: [1,3,4,5]
}
print(abstract['first']) # 123
print(abstract[True]) # 'hello
print(abstract[777]) # [1,3,4,5]
sample = {
'username': 'hisenberg',
'username': 'james'
}
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
house = {
'rooms' : 4,
'occupants': 2,
'doors': 6
}
print(house['windows']) # KeyError: 'windows'
#instead
print(house.get('windows')) # None
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
user = {'name': 'Raghav', 'age': 20, 'country': 'India'}
print('name' in user.keys()) # True
print('gender' in user.keys()) # False
print('Raghav' in user.values()) # True
Some other useful dictionary methods are copy, clear, pop, update
cat = {
'name': 'Tom',
'greet': 'meow',
'health': 100
}
cat_copy = cat.copy()
print(cat_copy) # {'name': 'Tom', 'greet': 'meow', 'health': 100}
cat.pop('name')
print(cat) # {'greet': 'meow', 'health': 100}
cat.clear()
print(cat) # {}
cat_copy.update({'name': 'Polo'})
print(cat_copy) # {'name': 'Polo', 'greet': 'meow', 'health': 100}
cat_copy.update({'color': 'Black'}) # adds key value if not present
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.
my_tuple = (1,2,3) # Can be any no of items
print(my_tuple[1]) # 2 (Values can be accessed just like lists)
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.
colors = ('red', 'orange', 'blue', 'yellow')
new_colors = colors[1:4]
print(new_colors) # ('orange', 'blue', 'yellow')
color_1,*others = colors # unpacking!
print(color_1) # 'red'
print(others) # ['orange', 'blue', 'yellow']
print(len(colors)) # 4
print(colors.count('red')) # 1
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.
set_of_numbers = {1,2,3,4,5,5}
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
emails = ['samantha@hey.com', 'rock@hey.com', 'samantha@hey.com']
emails_set = set(emails)
unique_emails = list(emails_set)
print(unique_emails) # ['rock@hey.com', 'samantha@hey.com']
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.
set_a = {1,2,3,4,5}
set_b = {4,5,6,7,8}
print(set_a.union(set_b)) # {1, 2, 3, 4, 5, 6, 7, 8}
print(set_a | set_b) # same as above just a compact syntax
print(set_a.intersection(set_b)) # {4, 5}
print(set_a & set_b) # same as above
set_a.discard(1)
print(set_a) # {2,3,4,5}
Python Set methods
Oh boy! finally done with the data basic building blocks of Python with a basic understanding of its data types.
Tomorrow the focus will to learn the conditional flow and iterations or looping in Python. I am pumped up now. Hope you have enjoyed following allowing as well π
Have a nice one!
Top comments (11)
Hi Arindam,
Another nice post. I thought you might be interested to know you don't need keys() to check if a key is in a dict. This is more idiomatic.
Similarly, we often use sets to deduplicate list and provide fast lookups because a set is stored as a hash of values.
The in keyword works on any iterable value... but I'm sure you will come to that soon enough. Enjoy your loops session. It's really cool stuff.
Cheers
Adrian
Thanks Adrian for the suggestion.
My intent was to demonstrate that keys() method is the default one. I forgot to mention explicitly.
I am so glad you found it worth a read :)
Good tutorial. Strangely though list(range(10)) does not seem to work on JupyterLab, but works seamlessly on Jupyter Notebook, it unfortunately took a while to figure this out... I assume you are coding in Jupyter Notebook? Also, for List Unpacking, lists with emojis did not work for me at all, was it supposed to?
TypeError Traceback (most recent call last)
in
7 print(merge_avengers) # ironman spiderman antman hulk
8
----> 9 range_of_numbers = list(range(10)) # quickly generates a list of specific range
10 print(range_of_numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
11 another_range = list(range(0,5)) # with start stop
TypeError: 'list' object is not callable
I am not using Jupyter Notebooks. I am using REPL to test my code.
Pardon me, but I was not able to understand the error message properly.
Can you try running the code in REPL or any python code editor?
returns list index out of range. Does not generate any list for me.
this does not work either. Returns list object is not callable...
Thank you for pointing that out. There was a typo in my post. I have rectified it now.
The first one should be list(range(10))
The second one should work fine. Where are you trying to evaluate this?
Generally, list index out of range occurs if we try to access an element in a list which is not present.
Yes it works
HI Arindam!
at the part of
user = {'name': 'Max', 'age': 40, 'married': False}
print(user['name']) # Max
print(user['married'] # False
u missed an ')' after ['married']
And it took me half an hour to figure π
HI Arindam!
It s me again.
I found another missing ')' , this time i was faster.
at the part of
print(abstract['first'] # 123
print(abstract[True]) # 'hello
print(abstract[777]) # [1,3,4,5]
after ['first']
π
Thanks Matt for taking the time to report this. Yeah sometimes it's the most silly things that we tend to ignore!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.