Python Programming
Topics:

List & Tuples

List is a collection of values separated by commas ',' and enclosed within `[]`.

List Representation


a = [1,2,3]
b = [1,2,3,]
c = [
	1,
	2,
	3
]
d = [
	1,
	2,
	3,
]
>>> a==b==c==d
True
e = [3,2,1,1,[4,5,['A',4,6]]]

>>> type([])


Empty list : []
To check for empty list: len(l)==0

Properties of list


1. Collection type

2. Indexes are in sequence
      0   1   2   3
l = ['A','B','C','D']
     -4  -3  -2  -1
	- indexing
	- slicing [start=0:end=len(list):step=1]
	- transformation to other sequences
		string : "".join([str(i) for i in l])
		tuple  : tuple(l)
		dictionary : {}.fromkeys(l,value=None)
					 dict(zip(key_list,value_list))
		set : set(list)

3. Values may be unordered
l = [213,412,35,1235]

4. Values may be redundant/duplicate
l = [4,1,2,3,2,2,1]

5. Mutable

Removing duplicates from list: list(set(l))
Removing duplicates from list and sorting it: sorted(set(l))
Sorting a list: sorted(set(l))

Difference b/w sort() and sorted()
===================================
sort() : It is a built-in list attribute,
it sorts the list mutably without returning a new list

sorted() : It is a builtin attribute that returns a sorted list from given sequence.

>>> l = [2,1,3]
>>> sorted(l)
[1, 2, 3]
>>> l
[2, 1, 3]
>>>
>>> l.sort()
>>> l
[1, 2, 3]
>>> sorted("apple")
['a', 'e', 'l', 'p', 'p']

clear() vs del
=================
del is a keyword that deletes the object.
clear() is list attribute that only clears list values leaving behind empty list.

len() vs count()
=================
len() is a python builtin function that returns total length of sequence.
count() is a list attribute that returns given element count, otherwise 0.


Define a list object
=======================
eval(input())

def function(l):
	...
function([])

# Example : Sort a given list
def function(l):
	l.sort()
	return l

print(function([3,1,2,4,6,5]))

Making a list
==================
Step 1: Get the size of list
Step 2: Define a new empty list
Step 3: Loop size times
Step 4: Ask for value each time
Step 5: Append each collected value in the new list

subjects = int(input("Enter number of subjects: "))
l = []
for i in range(subjects):
	marks = int(input("Enter the marks: "))
	l.append(marks)
print("List of marks:",l)

Weak attributes
=================
>>> l1 = [2,3,4]
>>> l2 = [5,6]
>>> l1+l2
[2, 3, 4, 5, 6]
>>> l1.__add__(l2) # read as, 'dunder add'
[2, 3, 4, 5, 6]
>>> l1>l2
False
>>> l1.__gt__(l2) # sequences are compared index-wise
False

>>> for i in range(len(a)):
...     if a[i]==3: print(i)
...
0
2
5
7
>>> for index,value in enumerate(a):
...     if value==3: print(index)
...
0
2
5
7


Built-in functions for a list object : dir(list)


'append'
'clear'
'copy'
'count'
'extend'
'index'
'insert'
'pop'
'remove'
'reverse'
'sort'

CRUD operation wise classification of list functions


CREATE : 'append', 'extend', 'insert', 'copy'
Read : 'count', 'index'
Update : 'reverse', 'sort'
Delete : 'clear', 'pop', 'remove'

List functions with example:


In [4]:
# For the examples below we will consider this list
l = [1,3,2,4,5,7,8,6]
In [5]:
# append: It puts the given value at the end of the list object
l.append(1)
print(l)
[1, 3, 2, 4, 5, 7, 8, 6, 1]
In [6]:
# append: It concatenates another list at the end of the first list.
l.extend([1,2,3])
print(l)
[1, 3, 2, 4, 5, 7, 8, 6, 1, 1, 2, 3]
In [7]:
# insert: It assigns the given value at a given index with the list. First parameter is index, second is value.
l.insert(0,100)
print(l)
[100, 1, 3, 2, 4, 5, 7, 8, 6, 1, 1, 2, 3]
In [8]:
l.insert(3,300)
print(l)
[100, 1, 3, 300, 2, 4, 5, 7, 8, 6, 1, 1, 2, 3]
In [9]:
l.insert(len(l),999)
print(l)
[100, 1, 3, 300, 2, 4, 5, 7, 8, 6, 1, 1, 2, 3, 999]
In [10]:
# count: It returns the count of a given value within the list.
print(l.count(1))
3
In [11]:
# index: It returns the first position of a given value within the list.
print(l.index(1))
1
In [12]:
# Print all indexes of a given value
for index,value in enumerate(l):
    if value==1:
        print(index)
1
10
11
In [13]:
# sort : It sorts the given list in ascending order.
l.sort()
print(l)
[1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 100, 300, 999]
In [14]:
# reverse: It reverses the given list horizontally.
l.reverse()
print(l)
[999, 300, 100, 8, 7, 6, 5, 4, 3, 3, 2, 2, 1, 1, 1]
In [15]:
# sort : It sorts the given list in the descending order.
l.sort(reverse=True)
print(l)
[999, 300, 100, 8, 7, 6, 5, 4, 3, 3, 2, 2, 1, 1, 1]
In [20]:
# sorting of strings is done based on ascii order
x = ['A','apple','a','Apple','APPLE']
x.sort()
print(x)
['A', 'APPLE', 'Apple', 'a', 'apple']
In [21]:
# pop: It pops the value at given index, default index is -1
value_removed = l.pop()
print(l)
print(value_removed)
[999, 300, 100, 8, 7, 6, 5, 4, 3, 3, 2, 2, 1, 1]
1
In [22]:
value_removed = l.pop(2)
print(l)
print(value_removed)
[999, 300, 8, 7, 6, 5, 4, 3, 3, 2, 2, 1, 1]
100
In [23]:
# remove: It removes first occurance of a given value.
l.remove(3)
print(l)
[999, 300, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1]
In [24]:
# clear: It clears all values from the list making it empty.
l.clear()
print(l)
[]
In [25]:
# append can also work with empty list by putting the value in the first place.
l.append(1)
print(l)
# Alternatively, use:  list_object += [value]
[1]
In [ ]:
# del : This keyword deletes a list object and clears all its values.
del l
# print(l) : NameError
In [28]:
# max : It gives the maximum value from a given list of numbers.
print(max([1,-9,45.9,23,2,2,78,9]))
78
In [29]:
# min : It gives the minimum value from a given list of numbers.
print(min([1,-9,45.9,23,2,2,78,9]))
-9
In [30]:
# sum : It gives the sum of values from a given list of numbers.
print(sum([1,-9,45.9,23,2,2,78,9]))
151.9
In [32]:
# shuffle : It is found in 'random' module. It shuffle the list values randomly
from random import shuffle
l = [1,2,3,4,5,6,7,9,8,0]
shuffle(l)
print(l)
[2, 4, 8, 7, 3, 0, 6, 5, 1, 9]

Practice Questions


In [33]:
# 1. Write a program to count the number of odd numbers in a given list.

def countOdd(l):
	count = 0
	for i in l:
		if i%2!=0:
			count += 1
	return count
In [ ]:
# 2. Write a program to add the number of odd numbers in a given list.

def addOdd(l):
	sum = 0
	for i in l:
		if i%2!=0:
			sum += i
	return sum
In [34]:
# 3. Write a program to return sorted odd numbers from a given list.

def sortedOdd(l):
	newlist = []
	for i in l:
		if i%2!=0:
			newlist.append(i)
	return sorted(newlist)
In [ ]:
# 4. Write a program to select common elements from two given lists.

def findCommon(l1,l2):
	commonList = []
	for i in l1:
		if i in l2:
			commonList.append(i)
	return commonList
In [35]:
# 5. Write a program to combine elements of two given lists.

def joinLists(l1,l2):
	return l1+l2
In [36]:
# 6. Write a program to find difference between two lists.

def subtractLists(l1,l2):
	differnceList = []
	for i in l1:
		if not i in l2:
			differnceList.append(i)
	return differnceList
In [37]:
# 7. Write a program to delete first and last elements from a given list, if present.

def deleteFirstLast(l1):
	if len(l)==0:
		return l
	elif len(l)==1:
		l.pop(0)
		return l
	else:
		l.pop(0)
		l.pop()
		return l
In [38]:
# 8. Write a program to find union of two given lists.
# Hint:  Union is adding two lists where duplicate values apper only once i.e, a U b = (a-b)+b

def unionList(l1,l2):
	differnceList = []
	for i in l1:
		if not i in l2:
			differnceList.append(i)
	return differnceList+l2
In [39]:
# 9. Write a program to find symmetric difference of two lists.
# Hint: Symmetric difference is combining non-mutual elements from two lists i.e, a ^ b : (a-b)+(b-a)

def symmetricDifference(l1,l2):
    l = []
    for i in l1:
        if not i in l2:
            l.append(i)
    for j in l2:
        if not j in l1:
            l.append(j)
    return l

In [49]:
# 10. BrainTeaser: In a list of audience names there can be so many duplicate names. Return a list with all indexes for the most common name.

def allIndexes(nameList):
    l = []
    countList = []
    for i in nameList:
        countList.append(nameList.count(i))
    print(countList)
    most_common_name = nameList[countList.index(max(countList))]
    print(most_common_name)
    for i,v in enumerate(nameList):
        if v==most_common_name:
            l.append(i)
    return l

Tuple

It is a read-only/non-mutable list. It can also be redundant, unordered and sequential collection like list.

Eg. 1,2,2,'A',5,4,1,-90.8

Properties of tuple

  • It is a collection like list
  • It can be unordered
  • It can have redundant/duplicate values
  • It has index in sequence
  • Unlike list, tuple is non-mutable
  • Tuples can be a key for a dictionary but it has to be completely non-mutable

    t = (1,2,4,3,1,1,1,1) print(type(t)) < class 'tuple' > print(t[0]) 1 print([1:]) (2, 4, 3, 1, 1, 1, 1)

Tuple is marked with a set of parenthesis. '()'

x = (1,2,5)
x = (1,2,5,)
x = (
    1,
    2,
    5,
)
x = 1,2,5

A group of values mostly defaults to a tuple.

x = 1,2,4,4,4,5
x = 1,2,4,4,4,5

def fun():
    return 1,"hello",3,4

x = fun()
print(type(x))

dir(tuple)

Read/Access : index, count

  • count() : It is the count of individual tuple item, juts like list.
  • index() : Just like list it gives the index for a value in tuple.

One value tuple is defined like:

t = (1,)
print(type(t))
< class 'tuple' >
t = 1,
print(type(t))
< class 'tuple' >

List comprehension

It is a comprehensive or simpler way to create a new list from an existing list, typically in one line.

  • Syntax: [expression for loop on the original list if condition]

Examples:

square a given list of numbers

l = [1,2,3,4,5]
l2 = []
for i in l:
    l2.append(i**2)
print(l2)

print([i**2 for i in [1,2,3,4,5]])

square of only odd items

l = [1,2,3,4,5]
l2 = []
for i in l:
    if i%2!=0: # i%2==1
        l2.append(i**2)
print(l2)

print([i**2 for i in [1,2,3,4,5] if i%2==0])

Set properties with list comprehension

a = ['Amar','Akbar','Anthony','Rahul','Sachin']
b = ['Sachin','Saurav','Rahul','Dhoni']

a&b: intersection

[i for i in a if i in j]
['Rahul','Sachin']

a|b: union

[i for i in a if not i in b]+b
['Amar','Akbar','Anthony','Rahul','Sachin','Saurav','Dhoni']

a-b: difference

[i for i in a if not i in b]
['Amar','Akbar','Anthony']

a^b or (a-b)+(b-a): symmetric difference

[i for i in a if not i in b]+[j for j in b if not j in a]
['Amar','Akbar','Anthony','Saurav','Dhoni']

zip list of keys and values to a dictionary

x = ['A','B','D','C','E']
y = [1,2,3,4,5]
dict(zip(x,y))
{'A': 1, 'C': 4, 'E': 5, 'B': 2, 'D': 3}