Python – Week 3 – Built-in Data Types – Part 2

Another important built-in datatype is Lists. Let’s try few examples.

Lists

Lists are essential to use while programming and Python gives you more freedom. Here’s how:

>>> a = [1, 2, 3, 4, 5] #Declaring the list a
>>> a
[1, 2, 3, 4, 5]
>>> min(a) #minimum value in list a
1
>>> max(a) #maximum value in list a
5
>>> sum(a) #sum of all values in a
15
>>> len(a) #length of elements in a
5
>>> b = [6, 7, 8, 9, 10]
>>> a + b #Concatenation
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 

Dictionaries

Being the only standard mapping type in Python, dictionaries are used to map keys to values. Here are a couple to ways to create a dictionary in Python:

>>> a = dict(A = 1, B = 2)
>>> b = {'A': 1, 'B': 2}

There are many other ways to create a dictionary as well. For simplicity, let’s stick with above-mentioned two ways as they are easy to remember. Also, if you happen to use a different way, please feel free to share why you use such method for dictionaries.

In the following code example, you will see that many operations can be conducted on dictionaries such as membership tests, deletion, and more.

>>> a = {'A': 1, 'B': 2}
>>> a['C'] = 3 #Assigning a new value to a new key
>>> 3 in a #Membership test
False
>>> 'C' in a #Membership test
True
>>> del a['C'] #Delete operation
>>> a
{'A': 1, 'B': 2}
>>> a.clear() #Clearing the entire dictionary
>>> a
{}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s