Day 8 & 9. Time to play with (Lists, Tuple, Sets & Dictionary in python).

Hello Everyone

Introduction

Collections in Python are containers that are used to store collections of data, for example, list, dictionary, set, tuple, etc. These are built-in collections. Several modules have been developed that provide additional data structures to store collections of data. One such module is the Python collections module.

Let’s Start

1. Lists.

How to create a list?

In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string, etc.).

# empty listmy_list = []# list of integermy_list = [1, 2, 3]# list with mixed datatypesmy_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called a nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. The index starts at 0. So, a list having 5 elements will have an index from 0 to 4.

my_list = ['p','a','n','k','a','j']# Output: pprint(my_list[0])# Output: nprint(my_list[2])# Output: aprint(my_list[4])# Error! Only integer can be used for indexing# my_list[4.0]# Nested Listn_list = ["Happy", [2,0,1,5]]# Nested indexing# Output: aprint(n_list[0][1])# Output: 5print(n_list[1][3])

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

my_list = ['p','a','n','k','a','j']# Output: jprint(my_list[-1])# Output: aprint(my_list[-5])

How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

my_list = ['s','i','d','d','h','a','r','t','h']# elements 3rd to 5thprint(my_list[2:5])# elements beginning to 4thprint(my_list[:-5])# elements 6th to endprint(my_list[5:])# elements beginning to endprint(my_list[:])

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need two indices that will slice that portion from the list.

How to change or add elements to a list?

List are mutable, meaning, their elements can be changed, unlike string or tuple.

We can use the assignment operator (=) to change an item or a range of items.

# mistake valuesodd = [2, 4, 6, 8]# change the 1st itemodd[0] = 1# Output: [1, 4, 6, 8]print(odd)# change 2nd to 4th itemsodd[1:4] = [3, 5, 7]# Output: [1, 3, 5, 7]print(odd)

We can add one item to a list using append() the method or add several items using extend() the method.

odd = [1, 3, 5]odd.append(7)# Output: [1, 3, 5, 7]print(odd)odd.extend([9, 11, 13])# Output: [1, 3, 5, 7, 9, 11, 13]print(odd)

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

odd = [1, 3, 5]# Output: [1, 3, 5, 9, 7, 5]print(odd + [9, 7, 5])#Output: ["re", "re", "re"]print(["re"] * 3)

Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

odd = [1, 9]odd.insert(1,3)# Output: [1, 3, 9]print(odd)odd[2:2] = [5, 7]# Output: [1, 3, 5, 7, 9]print(odd)

How to delete or remove elements from a list?

We can delete one or more items from a list using the keyword del. It can even delete the list entirely.

my_list = ['p','r','o','b','l','e','m']# delete one itemdel my_list[2]# Output: ['p', 'r', 'b', 'l', 'e', 'm']print(my_list)# delete multiple itemsdel my_list[1:5]# Output: ['p', 'm']print(my_list)# delete entire listdel my_list# Error: List not definedprint(my_list)

We can use remove() method to remove the given item or pop() method to remove an item at the given index.

The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

my_list = ['p','r','o','b','l','e','m']my_list.remove('p')# Output: ['r', 'o', 'b', 'l', 'e', 'm']print(my_list)# Output: 'o'print(my_list.pop(1))# Output: ['r', 'b', 'l', 'e', 'm']print(my_list)# Output: 'm'print(my_list.pop())# Output: ['r', 'b', 'l', 'e']print(my_list)my_list.clear()# Output: []print(my_list)

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

>>> my_list = ['p','r','o','b','l','e','m']>>> my_list[2:3] = []>>> my_list['p', 'r', 'b', 'l', 'e', 'm']>>> my_list[2:5] = []>>> my_list['p', 'r', 'm']

Python List Methods

Methods that are available with list object in Python programming are tabulated below.

They are accessed as list.method(). Some of the methods have already been used above.

Some examples of Python list methods:

my_list = [3, 8, 1, 6, 0, 8, 4]# Output: 1print(my_list.index(8))# Output: 2print(my_list.count(8))my_list.sort()# Output: [0, 1, 3, 4, 6, 8, 8]print(my_list)my_list.reverse()# Output: [8, 8, 6, 4, 3, 1, 0]print(my_list)

List Comprehension

List comprehension is an elegant and concise way to create a new list from an existing list in Python.

A list comprehension consists of an expression followed by for statement inside square brackets.

Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]print(pow2)

This code is equivalent to

pow2 = []for x in range(10):pow2.append(2 ** x)

A list of comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]>>> pow2[64, 128, 256, 512]>>> odd = [x for x in range(20) if x % 2 == 1]>>> odd[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]['Python Language', 'Python Programming', 'C Language', 'C Programming']

Iterating Through a List

Using a for the loop we can iterate through each item in a list.

for fruit in ['apple','banana','mango']:print("I like",fruit)

2. Tuple.

A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed.

Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses, separated by commas. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

# Empty tuplemy_tuple = ()print(my_tuple) # Output: ()# Tuple having integersmy_tuple = (1, 2, 3)print(my_tuple) # Output: (1, 2, 3)# tuple with mixed datatypesmy_tuple = (1, “Hello”, 3.4)print(my_tuple) # Output: (1, “Hello”, 3.4)# nested tuplemy_tuple = (“mouse”, [8, 4, 6], (1, 2, 3))# Output: (“mouse”, [8, 4, 6], (1, 2, 3))print(my_tuple)

A tuple can also be created without using parentheses. This is known as tuple packing.

my_tuple = 3, 4.6, “dog”print(my_tuple) # Output: 3, 4.6, “dog”# tuple unpacking is also possiblea, b, c = my_tupleprint(a) # 3print(b) # 4.6print(c) # dog

Creating a tuple with one element is a bit tricky.

Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.

my_tuple = (“hello”)print(type(my_tuple)) # <class ‘str’># Creating a tuple having one elementmy_tuple = (“hello”,)print(type(my_tuple)) # <class ‘tuple’># Parentheses is optionalmy_tuple = “hello”,print(type(my_tuple)) # <class ‘tuple’>

Access Tuple Elements

There are various ways in which we can access the elements of a tuple.

Indexing

We can use the index operator [] to access an item in a tuple where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an element outside of tuple (for example, 6, 7,…) will raise an IndexError.

The index must be an integer; so we cannot use float or other types. This will result in TypeError.

Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

my_tuple = (‘p’,’e’,’r’,’m’,’i’,’t’)print(my_tuple[0]) # ‘p’print(my_tuple[5]) # ‘t’# IndexError: list index out of range# print(my_tuple[6])# Index must be an integer# TypeError: list indices must be integers, not float# my_tuple[2.0]# nested tuplen_tuple = (“mouse”, [8, 4, 6], (1, 2, 3))# nested indexprint(n_tuple[0][3]) # ‘s’print(n_tuple[1][1]) # 4

Negative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

my_tuple = (‘p’,’e’,’r’,’m’,’i’,’t’)# Output: ‘t’print(my_tuple[-1])# Output: ‘p’print(my_tuple[-6])

Slicing

We can access a range of items in a tuple by using the slicing operator — colon “:”.

my_tuple = (‘s’,’i’,’d’,’d’,’h’,’a’,’r’,’t’,’h’)# elements 2nd to 4thprint(my_tuple[1:4])# elements beginning to 2ndprint(my_tuple[:-7])# elements 8th to endprint(my_tuple[7:])# elements beginning to endprint(my_tuple[:])

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.

Changing a Tuple

Unlike lists, tuples are immutable.

This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.

We can also assign a tuple to different values (reassignment).

my_tuple = (4, 2, 3, [6, 5])# TypeError: ‘tuple’ object does not support item assignment# my_tuple[1] = 9# However, item of mutable element can be changedmy_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])print(my_tuple)# Tuples can be reassignedmy_tuple = (‘p’,’r’,’o’,’g’,’r’,’a’,’m’,’i’,’z’)# Output: (‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘i’, ‘z’)print(my_tuple)

We can use + operator to combine two tuples. This is also called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result in a new tuple.

# Concatenation# Output: (1, 2, 3, 4, 5, 6)print((1, 2, 3) + (4, 5, 6))# Repeat# Output: (‘Repeat’, ‘Repeat’, ‘Repeat’)print((“Repeat”,) * 3)

Deleting a Tuple

As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.

But deleting a tuple entirely is possible using the keyword del.

my_tuple = (‘s','i','d','d','h','a','r','t','h')# can’t delete items# TypeError: ‘tuple’ object doesn’t support item deletion# del my_tuple[3]# Can delete an entire tupledel my_tuple# NameError: name ‘my_tuple’ is not definedprint(my_tuple)

Tuple Methods

Methods that add items or remove items are not available with a tuple. Only the following two methods are available.

Python Tuple MethodMethodDescriptioncount(x)Returns the number of items xindex(x)Returns the index of the first item that is equal to x

Some examples of Python tuple methods:

my_tuple = (‘a’,’p’,’p’,’l’,’e’,)print(my_tuple.count(‘p’)) # Output: 2print(my_tuple.index(‘l’)) # Output: 3

3. Sets.

A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed).

However, the set itself is mutable. We can add or remove items from it.

Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.

Create a Set.

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set().

# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Change set in program.

Sets are mutable. But since they are unordered, indexing have no meaning.

We cannot access or change an element of set using indexing or slicing. Set does not support it.

We can add single element using the add() method and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.

# initialize my_set
my_set = {1,3}
print(my_set)
#my_set[0]# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)

Remove elements from sets.

A particular item can be removed from set using methods, discard() and remove().

The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition.

The following example will illustrate this.

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# If you uncomment line 27,
# you will get an error.
# Output: KeyError: 2
#my_set.remove(2)

Python set operations.

Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}>>> B = {4, 5, 6, 7, 8}

Iterating Through a Set.

Using a for loop, we can iterate though each item in a set.

>>> for letter in set("apple"):...     print(letter)...apel

4. Dictionary.

A dictionary is a collection which is unordered, changeable and indexed, in python dictionaries are written with curly brackets. and they have keys and values.

Create a dictionary.

dict1 = {
"Bread":"Ford",
"Model":"Mustang",
"Year": "2019"}
print(dict)

Accessing items.

You can access the items of a dictionary by referring to its key name, inside square brackets:

see = dict1["Model"]print(see)#also we can use get method hereview = dict1.get("Model")

Change value.

Here you can change the value in the present dictionary.

dict1[year] = 2020

Loops in the dictionary.

you can also use the value() function to return values of a dictionary.

for x in dict1.value()
print(x)

loop through both kays and values, by using the items() functions:-

for x, y in dict.item():
print(x,y)

Adding items.

In dictionary we can also add new items with the present one.

dict1["color"] = "red"
print(dict1)

Removing items.

The pop() method remove the item with the specified key name.

dict1.pop("model")
print(dict1)

Nested dictionaries.

A dictionary can also contain many dictionaries, this is called nested dictionaries.

myfamily = {
"child": {
"name":"john",
"year":"2004"
},
"child2":{
"name":"emmy"
"year":"2007"
},
}

Thank You

Data Scientist, Blockchain enthusiast, Entrepreneur.