Chapter 3: Collection Data Types - VinGok/Python-Basics GitHub Wiki
Collection data type - A data type that supports storage of heterogeneous data types, and is iterable. Python provides four collection data types:
- tuple
- list
- set
- dictionary
Tuple
Tuples are collection of one or more object references. Tuples are immutable. It means once loaded no item can be replaced or deleted. Tuples preserve the order of the items.
->>> name= (28.6, "python", 23, 'basics')
->>> print(name, type(name))
(28.6, 'python', 23, 'basics') <class 'tuple'>
->>> name = ()
->>> type(t1)
<class 'tuple'>
->>> name= (28.6, "python", 23, 'basics')
->>> print(name[:], name[::-1])
(28.6, "python", 23, 'basics') ('basics', 23, "python", 28.6)
->>> name[0] = name[0] + 10
TypeError: 'tuple' object does not support item assignment
->>> name= (28.6, "python", 23, 'basics')
->>> name += ("Thursday",)
->>> print(name)
(28.6, "python", 23, 'basics', 'Thursday')
->>> things = (1, -7.5, ("pea", (5, "Xyz"), "queue"))
->>> things[2][1][1][2]
'z'
->>> print(len(things))
3
->>> for i in things:
->>> print(i)
1
-7.5
('pea', (5, 'Xyz'), 'queue')
->>> tuple("Python")
('P', 'y', 't', 'h', 'o', 'n')
Tuple Methods:
Syntax | Description |
---|---|
T.index(x) | Returns the index of item x in tuple T |
L.count(x) | Returns the number of times item x occurs in tuple T |
Examples:
1. Count the number of tuple elements that consist of only alphabets.
tuple_example= ('12', '13.45', 'JCU', 'www.Books12.com', 'PrF', 'Science')
tuple_example= ('12', '13.45', 'JCU', 'www.Books12.com', 'PrF', 'Science')
count = 0
for i in tuple_example:
if i.isalpha():
count = count + 1
print(count)
2. Add all the float elements present in (('forest', 13.34), (True, False, 12.56), (True, 'random', 'string', 10.00))
name = (('forest', 13.34), (True, False, 12.56), (True, 'random', 'string', 10.00))
sum_float = 0
for i in name:
sum_float = sum_float + i[-1]
print(sum_float)
Programming Examples:
1. Extract the character S from the tuple (1, 2, (34, 12.36, "wheat", (1, ("WEST",), "box")))
2. Given the below tuple containing the company and it's corresponding yearly profit (in million units). Add the profits of all companies beginning with the same alphabet (case=insensitive), and print the alphabet-wise profits.
(('Google', 10.6), ('quora', 0.6), ('godrej', 6.76), ('Microsoft', 6.8), ('alibaba', 2.54), ('Amazon', 9.6), ('Moneta', 2.32), ('BMW', 22.6))
Expected Output:
G: 17.36
Q: 0.6
M: 9.12
A: 12.14
B: 22.6
Lists
Lists are collections of one or more heterogeneous object references. Lists are mutable. It means items can be added, replaced, and deleted. Tuples preserve the order of the items.
->>> things = [1, 2, 'a', 'b']
->>> print(things, type(things))
[1, 2, 'a', 'b'] <class 'list'>
->>> a = [1, 2, 3, "python"]
->>> a[3] = "basics"
->>> print(a)
[1, 2, 3, 'basics']
->>> a = [1, 2, 3, "python"]
->>> a[3][2] = "Z"
TypeError: 'str' object does not support item assignment
->>> b = [1, 2, 3, 'basics', (-6.88, "biology", "genomics", False), "nature"]
->>> print(b[4][1][6])
'y'
->>> b[4][1].strip('goly')
'bi'
->>> course = "Python basics"
->>> print(list(course))
['P', 'y', 't', 'h', 'o', 'n', ' ', 'b', 'a', 's', 'i', 'c', 's']
->>> course = "Python basics"
->>> print(tuple(course))
('P', 'y', 't', 'h', 'o', 'n', ' ', 'b', 'a', 's', 'i', 'c', 's')
List Methods
Syntax | Description |
---|---|
L.append(x) | Adds item x as a whole to the end of list L |
L.extend(x) | Adds level-1 elements of item x individually to the end of list L (equivalent to operation +) |
L.count(x) | Returns the number of times item x occurs in list L at level-1 |
L.index(x,start,end) | Returns the index position of the leftmost occurrence of item x in list L (or in the start:end slice of L ) at level-1; otherwise, raises a ValueError exception |
L.insert(i, x) | Inserts item x into list L at index i |
L.pop() | Returns and removes the rightmost item of list L at level-1 |
L.pop(i) | Returns and removes the item at index i of list L |
L.remove(x) | Removes the leftmost occurrence of item x from list L at level-1, or raises a ValueError exception if x is not found |
L.reverse() | Reverses list L in-place at level-1 |
L.sort(key = , reverse = ) | Sorts list L in-place at level-1; key argument specifies the rule for sorting, reverse specifies ascending or descending order. Both key and reverse are optional |
->>> course = ["Python basics"]
->>> another_course = ["Python advanced"]
->>> course.append(another_course)
->>> print(course)
['Python basics', ['Python advanced']]
->>> course = ["Python basics", ['Python advanced']]
->>> course[1].append('runs every Friday')
->>> print(course)
['Python basics', ['Python advanced', 'runs every Friday']]
->>> course = ['Python basics', ['Python advanced', 'runs every Friday']]
->>> course.count("Python advanced")
0
->>> course = ['Python basics', ['Python advanced', 'runs every Friday']]
->>> course[1].count("Python advanced")
1
->>> course = ['Python basics', ['Python advanced', 'runs every Friday']]
->>> course.count("Python basics")
1
->>> course = ['Python basics', ['Python advanced', 'runs every Friday']]
->>> course.insert(1, 'runs every Thursday')
->>> print(course)
['Python basics', 'runs every Thursday', ['Python advanced', 'runs every Friday']]
->>> course = ['Python basics', 'runs every Thursday', ['Python advanced', 'runs every Friday']]
->>> len(course)
3
->>> len(course[0])
13
->>> len(course[2][0])
15
->>> course = ['Python basics', 'runs every Thursday', ['Python advanced', 'runs every Friday']]
->>> course[1].split(" ")
['runs', 'every', 'Thursday']
->>> course[0] = "today"
->>> print(course)
['today', 'runs every Thursday', ['Python advanced', 'runs every Friday']]
->>> course = ['Python basics', 'runs every Thursday', ['Python advanced', 'runs every Friday']]
->>> course.reverse()
->>> print(course)
[['Python advanced', 'runs every Friday'], 'runs every Thursday', 'Python basics']
->>> course = [['Python advanced', 'runs every Friday'], 'runs every Thursday', 'Python basics']
->>> course[0].reverse()
->>> print(course)
[['runs every Friday', 'Python advanced'], 'runs every Thursday', 'Python basics']
->>> a = (1, 2, 3, (4, 5))
->>> b = list (a)
->>> print(a, b)
(1, 2, 3, (4, 5)) [1, 2, 3, (4, 5)]
->>> b = [1, 2, 3, (4, 5)]
->>> c = tuple(b)
->>> print(c, b)
(1, 2, 3, (4, 5)) [1, 2, 3, (4, 5)]
Examples:
1. Generate a list of all even integers from 1 to 100
list_int = []
for j in range(1, 101):
if (j%2 == 0):
list_int.append(j)
print(list_int)
Programming Examples
1. Generate a list of Fibonacci number series with 20 elements starting with the list [0, 1].
2. In the list ['python', 'basics', 'Penguin', 'Thursday', 'tramway', 'beadS', 'PhotoN'], group all items that start and end with the same alphabets irrespective of their case. Specifically, display
['python', 'Penguin', 'PhotoN', 'basics', 'breadS', 'Thursday', 'tramway'].
Function:
number_1 = 21
if (number_1%2 == 0):
print("{0} is even".format(number_1))
else:
print("{0} is odd".format(number_1))
number_2 = 102
if (number_2%2 == 0):
print("{0} is even".format(number_2))
else:
print("{0} is odd".format(number_2))
number_3 = 201
if (number_3%2 == 0):
print("{0} is even".format(number_3))
else:
print("{0} is odd".format(number_3))
Functions are reusable pieces of code that can be called from any part of the program.
def user_func(x):
if (x%2 == 0):
print("{0} is even".format(x))
else:
print("{0} is odd".format(x))
number_1 = 21
user_func (number_1)
number_2 = 102
user_func (number_2)
number_3 = 201
user_func (number_3)
Function for adding digits in an integer
def user_func(x):
addition = 0
y = str(x)
for i in y:
addition = addition + int(i)
return addition
number_1 = 21
sum_of_digits = user_func (number_1)
print("Sum of digits of {0} is {1}".format(number_1, sum_of_digits))
number_2 = 1024
sum_of_digits = user_func (number_2)
print("Sum of digits of {0} is {1}".format(number_2, sum_of_digits))
number_3 = 780
sum_of_digits = user_func (number_3)
print("Sum of digits of {0} is {1}".format(number_3, sum_of_digits))
List sorting
->>> a = [23, 31, -1, 0.25, 100, -36.45]
->>> a.sort()
->>> print(a)
[-36.45, -1, 0.25, 23, 31, 100]
->>> a = [23, 31, -1, 0.25, 100, -36.45]
->>> a.sort(reverse = True)
->>> print(a)
[100, 31, 23, 0.25, -1, -36.45]
->>> b = ["python", "basics", "every", "thursday"]
->>> b.sort()
->>> print(b)
['basics', 'every', 'python', 'thursday']
Note: Observe that all list methods modify the list contents in-place. This is due to mutability property of lists.
Example
1. Sort the list ["python", "basics!", "every", "thursday"] in the ascending order based on the string lengths.
list_strings = ["python", "basics!", "every", "thursday"]
list_strings.sort(key = len)
print(list_strings)
2. Sort the list ["its", "and", "mount", "other", "ranges", "elegant"] in the ascending order based on the last character in the string.
list_strings = ["its", "and", "mount", "other", "ranges", "elegant"]
def user_func (x):
return x[-1]
list_strings.sort(key = user_func)
print(list_strings)
3. Sort the list [21, 1024, 332, 2052, 431, 19] in the ascending order based on the two parameters in the following order:
(i) number of digits, (ii) last digit.
def user_func(x):
y = str(x)
return len(y), y[-1]
list_int = [21, 1024, 332, 2052, 431, 19]
list_int.sort(key = user_func)
print(list_int)
4. Sort the list elements in the ascending order of the second items of the tuple.
def user_func(x):
return x[1]
list_tuple = [(2, 2), (3, 4), (4, 1), (1, 3)]
list_tuple.sort(key = user_func)
print(list_tuple)
Use of tuples over lists: If the items in a sequence are static, use tuples as they exhibit much lesser execution time than lists.
Programming practice
1. Sort the elements of the tuple based on the following parameters: (i) vowel count, (ii) string length, (iii) first character.
tuple_string = ("theory", "finding", "year end", "practice", "make", "elegant")
Output: ('make', 'theory', 'finding', 'elegant', 'practice', 'year end')
Sets
- unordered collection data type
- can contain only immutable data types
- unique items
- useful while checking for the existence of items in a sequence
->>> names = {'python', 100, 29.906, 100}
->>> print(type(names))
<class 'set'>
->>> print(names)
{100, 29.906, 'python'}
->>> print(names[1])
TypeError: 'set' object does not support indexing
->>> names = {1, 2, [3, 4]}
->>> print(names)
TypeError: unhashable type: 'list'
## unhashable broadly refers to mutable
->>> names = {21, 2, (-1, 1)}
->>> print(names)
{(-1, 1), 2, 21}
Set Methods and Operators
Syntax | Description |
---|---|
s.add(x) | Adds item x to set s if it is not already in s |
s.difference(t) or s - t | Returns a new set that has every item that is in set s but not in set t |
s.intersection(t) or s & t | Returns a new set that has each item that is in both set s and set t |
s.union(t) or s | t | Returns a new set that has all items common in sets s and t |
->>> a = {0, ('x', 11), 'sun', 'lion', 'veil'}
->>> b = {'tiger', 'wild cat', 'cheeta', 'lion'}
->>> a|b # union
{0, 'sun', 'lion', 'cheeta', 'tiger', ('x', 11), 'veil', 'wild cat'}
->>> a&b # intersection
{'lion'}
->>> a-b # difference
{0, ('x', 11), 'veil', 'sun'}
->>> int_tuple = (2,4,3,1,3)
->>> int_set = set(int_tuple)
->>> print(int_set)
{1, 2, 3, 4}
->>> int_set = {1, 2, 3, 4}
->>> int_list = list(int_set)
->>> print(int_list)
[1, 2, 3, 4]
Note: Since tuples do not support ordering of elements, the concept of indexing is invalid here.
->>> string_set = {"the", "winter", "is", "coming"}
->>> print(string_set[2])
TypeError: 'set' object does not support indexing
Other Set Methods
Syntax | Description |
---|---|
s.clear() | Removes all the items from set s |
s.isdisjoint(t) | Returns True if set s s and t have no items in common |
s.issubset(t) or s <= t | Returns True if set s is equal to or a subset of set t ; use s < t to test whether s is a proper subset of t |
s.issuperset(t) or s >= t | Returns True if set s is equal to or a superset of set t ; use s > t to test whether s is a proper superset of t |
s.remove(x) | Removes item x from set s , or raises a KeyError exception if x is not in s |
Programming Practice
3. Below are two lists: first one with usernames of students who are accessing Github repository, and the second one with usernames of students who are accessing elearning portal.
students_github = ["wienek00", "ramadj00", "martil13", "tolarn00", "fuadta00", "brabej08", "henned00", "matsya00"]
students_elearning = ["fuadta00", "tolarn00", "attarb00", "ahmedr00", "evieok00", "frankf00", "matsya00", "franzb00"]
Write a Python program to determine
(i) students who are accessing both Github and elearning
(ii) students who are accessing elearning but not Github
(iii) students who are accessing at least one of the two.
List Example:
names = ["mountain ranges", "mighty nature", "Himalayas", "Kaveri"]
for i in names:
if (len(i) > 10):
names.remove(i)
print(names)
Copying Data Types
Assigning a value to a variable is nothing but binding the variable to the reference. There are three different types of copying in Python.
Assignment
- binds the copy to the same reference
## Assignment operation without change of reference
->>> parent = [1, 2, 3]
->>> child = parent
->>> print (parent, child)
[1, 2, 3] [1, 2, 3]
->>> print(id(parent), id(child))
->>> child.append(4)
->>> print (child, parent)
[1, 2, 3, 4] [1, 2, 3, 4]
->>> parent.append(5)
->>> print (child, parent)
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
Shallow copy
- one level deeper copying than assignment
- copies the references for level-1 objects
- slicing is nothing but shallow copying
## Modifying a list of lists
->>> import copy
->>> a = [[1,2],7,8]
->>> b = copy.copy(a)
->>> print(a)
[[1,2],7,8]
->>> print(b)
[[1,2],7,8]
->>> a[0].append(9)
->>> print(a)
[[1, 2, 9], 7, 8]
->>> print(b)
[[1, 2, 9], 7, 8]
## Append an item to a list
->>> a = [[1,2],7,8]
->>> b = copy.copy(a)
->>> print(a)
[[1,2],7,8]
->>> print(b)
[[1,2],7,8]
->>> a.append(9)
->>> print(a)
[[1, 2], 7, 8, 9]
->>> print(b)
[[1, 2], 7, 8]
## Append tuple
->>> a = [(1,2),7,8]
->>> b = copy.copy(a)
->>> print(a)
[(1, 2), 7, 8]
->>> print(b)
[(1, 2), 7, 8]
->>> a[0] = a[0] + (9,10)
->>> print(a)
[(1, 2, 9, 10), 7, 8]
->>> print(b)
[(1, 2), 7, 8]
Deep copy
- one level deeper copying than shallow copy
- creates new copy of the data; changes in a variable have no influence on the other
## Deep copy operation
->>> import copy
->>> a = [[1,2,3],[4,5,6],7,8]
->>> b = copy.deepcopy(a)
->>> print(a)
[[1, 2, 3], [4, 5, 6], 7, 8]
->>> print(b)
[[1, 2, 3], [4, 5, 6], 7, 8]
->>> a[0].append(9)
->>> print(a)
[[1, 2, 3, 9], [4, 5, 6], 7, 8]
->>> print(b)
[[1, 2, 3], [4, 5, 6], 7, 8]
Note:
- Shallow and deep copies give different outcomes only in case of compound objects like list of lists. For simple lists they generate the same outcome.
- For simple objects (like lists), use assignment when you need the change in one to reflect on the other; otherwise use shallow copy. For compound objects, use shallow copy when you need change in one to reflect on the other; otherwise use deep copy.
Dictionaries
- unordered collection of key–value pairs
- keys must be immutable objects (int, float, string, tuple) and unique to the dictionary
- values may be objects of any type i.e. mutable or immutable; can be non-unique
- mutable data type - can add, modify, replace items
List v/s dictionary example:
In the below sequence consisting of companies and their corresponding profits, find the profit of the company Godrej.
[('Google', 10.6), ('Quora', 0.6), ('Godrej', 6.76), ('Microsoft', 6.8)]
## Using lists
list_company = ['Google', 10.6], ['quora', 0.6], ['Godrej', 6.76], ['Microsoft', 6.8](/VinGok/Python-Basics/wiki/'Google',-10.6],-['quora',-0.6],-['Godrej',-6.76],-['Microsoft',-6.8)
for i in list_company:
if (i[0] == "Godrej"):
print ("Godrej's profit = ", i[1])
break
## Using dictionaries
list_company = ['Google', 10.6], ['quora', 0.6], ['Godrej', 6.76], ['Microsoft', 6.8](/VinGok/Python-Basics/wiki/'Google',-10.6],-['quora',-0.6],-['Godrej',-6.76],-['Microsoft',-6.8)
dictionary = dict(list_company)
print("Godrej's profit = ", dictionary['Godrej'])
->>> dictionary = {'size': 3, 'id': 1948, 'name': "Washer"}
->>> print(dict_1, type(dict_1))
{'size': 3, 'id': 1948, 'name': 'Washer'} <class 'dict'>
->>> dictionary = {1: ["random", 3.45, ("hello", 2)], ("tuple", "as", "key"): ["list", "as", "value"]}
->>> print(dictionary[1][1])
3.45
->>> dictionary = {1: ["random", 3.45, ("hello", 2)], ("tuple", "as", "key"): ["list", "as", "value"]}
->>> print(dictionary[("tuple", "as", "key")])
["list", "as", "value"]
->>> dictionary = {1: ["random", 3.45, ("hello", 2)], ("tuple", "as", "key"): ["list", "as", "value"]}
->>> dictionary[1].append(-239)
->>> print(dictionary[1])
['random', 3.45, ('hello', 2), -239]
->>> dictionary = {1: ["random", 3.45, ("hello", 2)], ("tuple", "as", "key"): ["list", "as", "value"]}
->>> print(dictionary[1][0].split('n'))
['ra', 'dom']
->>> dictionary = {1: {1: "A", 2: "B", 3: "C"}, (3, 4, 5): [6, 7, 8]}
->>> dictionary[1][2] = "D"
->>> print(dictionary)
{1: 'A', 2: 'D', 3: 'C'}
->>> list_int = [(1, "this"), (2, "is"), (5, "an"), (6, "example")]
->>> dictionary = dict(list_int)
{1: 'this', 2: 'is', 5: 'an', 6: 'example'}
->>> tuple_int = ((1, "this"), (2, "is"), (5, "an"), (6, "example"))
->>> dictionary = dict(tuple_int)
{1: 'this', 2: 'is', 5: 'an', 6: 'example'}
->>> set_int = {(1, "this"), (2, "is"), (5, "an"), (6, "example")}
->>> dictionary = dict(set_int)
->>> print(dictionary)
{2: 'is', 1: 'this', 6: 'example', 5: 'an'}
->>> list_int = [1, 2, 3]
->>> print(dict(list_int))
TypeError: cannot convert dictionary update sequence element #0 to a sequence
->>> list_int = [(1, 2), (3, 4, 5)]
->>> print(dict(list_int))
ValueError: dictionary update sequence element #1 has length 3; 2 is required
->>> dictionary = {1: 'this', 2: 'is', 5: 'an', 6: 'example'}
->>> dictionary[3] = "just"
->>> print(dictionary)
{1: 'this', 2: 'is', 5: 'an', 6: 'example', 3: 'just'}
->>> dictionary = {1: 'this', 2: 'is', 5: 'an', 6: 'example'}
->>> dictionary[2] = "just"
->>> print(dictionary)
{1: 'this', 2: 'just', 5: 'an', 6: 'example'}
Built-in Dictionary Methods
Syntax | Description |
---|---|
d.keys() | Returns an iterable of all the keys in dict d |
d.values() | Returns an iterable of all the values in dict d |
d.items() | Returns an iterable all the (key, value) pairs in dict d |
d.get(k) | Returns key k's associated value, or None if k is not in dict d |
d.get(k, v) | Returns key k's associated value, or v if k is not in dict d |
d.pop(k) | Returns key k's associated value and removes the item whose key is k, or raises a KeyError exception if k isn’t in d |
d.setdefault(k, v) | The same as the dict.get() method, except that if the key is not in dict d, a new item is inserted with the key k, and with a value of None or of v if v is given |
Dictionary Examples:
1. Print the dictionary keys along with the corresponding values.
## Approach 1
dictionary = {"apple": 9, "orange": 5, "grape": 10}
for i in dictionary.keys():
print(i, dictionary[i])
## Approach 2
dictionary = {"apple": 9, "orange": 5, "grape": 10}
for i in dictionary.values():
print(i)
## Approach 3
dictionary = {"apple": 9, "orange": 5, "grape": 10}
for i, j in dictionary.items():
print(i, j)
2. Calculate the total price of each group present from the below dictionaries.
quantity = {"apple": 9, "orange": 5, "grape": 10}
price = {"grape": 35, "apple": 50, "orange": 60}
quantity = {"apple": 9, "orange": 5, "grape": 10}
price = {"grape": 35, "apple": 50, "orange": 60}
for i in quantity.keys():
total = quantity[i]*price[i]
print("Total price of {0}s is {1}".format(i, total))
3. From the below dictionary, add all profits of Google from year 2008 and 2010.
{2008: {"Google": 10.98, "Nokia": 3.45}, 2009: {"Nokia": 4.67}, 2010: {"Google": 9.89}}
## Wrong approach
profits_year = {2008: {"Google": 10.98, "Nokia": 3.45}, 2009: {"Nokia": 4.67}, 2010: {"Google": 9.89}}
profit = 0
for i in profits_year.values():
profit = profit + i["Google"]
print("Google's profit: ", profit)
## Wrong approach
profits_year = {2008: {"Google": 10.98, "Nokia": 3.45}, 2009: {"Nokia": 4.67}, 2010: {"Google": 9.89}}
profit = 0
for i in profits_year.values():
profit = profit + i.get("Google")
print("Google's profit: ", profit)
## Correct approach
profits_year = {2008: {"Google": 10.98, "Nokia": 3.45}, 2009: {"Nokia": 4.67}, 2010: {"Google": 9.89}}
profit = 0
for i in profits_year.values():
profit = profit + i.get("Google", 0)
print("Google's profit: ", profit)
4. Below are two dictionaries dict1 and dict2. Add the keys of dict2 along with their values that are not present in dict1. For keys of dict2 that are already present in dict1, do not add update.
dict1 = {1: "a", 2: "b", 3: "c", 9: "e"}
dict2 = {2: "f", 4: "b", 6: "c", 1: "e"}
for i in dict2.keys():
dict1.setdefault(i, dict2[i])
print(dict1)
Programming Practice
1. Calculate the total price of entire stock from the below dictionaries.
quantity = {"apple": 9, "orange": 5, "grape": 10}
price = {"grape": 35, "apple": 50, "orange": 60}
2. Below are two dictionaries: names containing author registration numbers (keys) and author names (values), and books containing author registration numbers (keys) and number of published articles (values). Write a python program to list the registration number, name, and number of published books of all author whose first and/or second names begin with 'S'.
names = {1140 : "Sally Floyd", 1156 : "Steven Low", 1157: "Hari Balakrishnan", 1136: "Subhasis Chaudhuri", 1142: "Keith Ross", 1190 : "Mark Handley", 1185: "Ben Shneiderman", 1179: "Alex Smola", 1165: "Henning Schulzrinne", 1197: "Jim Kurose"}
books = {1185: 5, 1140 : 14, 1157: 17, 1136: 10, 1156 : 23, 1142: 8, 1190 : 11, 1179: 8, 1165: 6, 1197: 7}
Iterables and Iterators
An iterable is an entity that can be iterated over in order to access successive items. For example, string, list, tuples, set, and dictionary are all iterables.
An iterator is an object that provides access to each item in an iterable.
Common Iterable Operators and Functions
Syntax | Description |
---|---|
s + t | Returns a sequence that is the concatenation of sequences s and t |
s * n | Returns a sequence that is int n concatenations of sequence s |
x in i | Returns True if item x is present in iterable i ; use not in to reverse the test |
len(x) | Returns the length of the iterable x at level-1. |
max(i, key) | Returns the biggest item in iterable i or the item with the biggest key value if a key function is specified |
min(i, key) | Returns the smallest item in iterable i or the item with the smallest key(item) value if a key function is given |
reversed(i) | Returns an iterator of items from iterable i in reverse order |
enumerate(i,start) | Returns an iterator for sequence of (index, item) tuples with indexes starting at 0 or start; normally used in for ... in loops |
zip(i1,..., iN) | Returns an iterator of tuples using the iterables i1 to iN |
sorted(i,key,reverse) | Returns a list of the items from iterator i in ascending order; key is used to specify sorting parameter. If reverse is True the sorting is done in descending order. |
sum(i,start) | Returns the sum of the items in iterable i plus start (which defaults to 0); i may not contain strings |
all(i) | Returns True if every item in iterable i evaluates to True |
any(i) | Returns True if any item in iterable i evaluates to True |
Examples
1. Check whether the key apple is present in dictionary price.
price = {"grape": 35, "apple": 50, "orange": 60}
print("apple" in price.keys())
2. Check whether the key peach is present in dictionary price.
price = {"grape": 35, "apple": 50, "orange": 60}
fruits = set(price.keys())
print('peach' in fruits)
3. Find the element with maximum length.
languages = ('Python', 'C++', 'Java', 'Perl')
print(max(languages, key = len))
4. Find the maximum number in the below list.
numbers = [16, 29, 35, 90, 65, 167, 98]
print(max(numbers))
5. Find the number with highest last digit
numbers = [16, 29, 35, 90, 65, 167, 98]
## Method 1
def last(num):
return num%10
print (max(numbers, key=last))
## Method 2
def last(num):
num = str(num)
return int(num[-1])
print (max(numbers, key=last))
5. Find the longest element in the list; in case of conflict find the one with highest number of vowels.
languages = ['Python', 'C++', 'Java', 'Perl', 'George']
def largest(lang):
count = 0
for i in lang:
if i.lower() in "aeiou":
count = count + 1
return len(lang), count
## Method 1
languages.sort(key = largest, reverse = True)
print(languages[0])
## Method 2
print (max(languages, key=largest))
6. Reversing a tuple
languages = ('Python', 'C++', 'Java', 'Perl', 'George')
## Method 1
print(languages[::-1])
## Method 2
print(tuple(reversed(languages)))
7. Display list elements along with their corresponding indices.
languages = ['Python', 'C++', 'Java', 'Perl']
## Method 1
count = 0
for i in languages:
print("{0} is at index {1}".format(i, count))
count = count + 1
print()
## Method 2
for i, j in enumerate(languages):
print ("{0} is at index {1}".format(j, i))
8. Assign student registration numbers starting from 11100 and print the names and corresponding numbers.
students = ['Alex', 'Veronika', 'Martin', 'Sowmya']
## Method 1
regNo = 11100
list_new = []
for i in students:
list_new.append((regNo, i))
regNo = regNo+1
print(list_new)
print()
## Method 2
list_new = list(enumerate(students, 11100))
print(list_new)
9. Enumerate dictionary keys.
profits = {"Google": 10.98, "Nokia": 3.45, "Siemens": 2.67}
## Method 1
print(list(enumerate(profits.keys())))
print()
## Method 2
print(list(enumerate(profits)))
10. Zipping lists.
names = ['Alex', 'Veronika', 'Martin', 'Sowmya']
score = [10, 30, 20, 19]
## Method 1
list_new = []
for i in range (0, len(names)):
list_new.append((names[i], score[i]))
print(list_new)
print()
## Method 2
list_new = list(zip(names, score))
print(list_new)
11. Zipping dictionaries.
prices = {
'Lakme': 45.23,
'Schwarzkopf': 612.78,
'Nivea': 205.55,
'Ponds': 37.20,
'Pantene': 10.75
}
## Method 1
list_prices = []
for i in prices:
list_prices.append((i, prices[i]))
print(list_prices)
## Method 2
print(list(zip(prices.keys(), prices.values())))
12. Find the item with the highest price.
prices = {
'Lakme': 45.23,
'Schwarzkopf': 612.78,
'Nivea': 205.55,
'Ponds': 37.20,
'Pantene': 10.75
}
print(max(zip(prices.values(), prices.keys())))
13. Sort the dictionary items in the increasing order of their price.
prices = {
'Lakme': 45.23,
'Schwarzkopf': 612.78,
'Nivea': 205.55,
'Ponds': 37.20,
'Pantene': 10.75
}
## Method 1
def user(item):
return prices[item]
list_keys = list(prices.keys())
list_keys.sort(key = user)
list_sorted = []
for i in list_keys:
list_sorted.append((i, prices[i]))
print(list_sorted)
## Method 2
print(sorted(zip(prices.values(), prices.keys())))
Programming Practice:
7. In the below dictionary, sort the items of each year in the ascending order of their profits, and in case of conflict sort them in the descending order of lengths of company names.
companies = {2008: {"Google": 10.98, "Nokia": 3.45, "Samsung": 10.98},
2009: {"Google": 3.27, "Nokia": 4.67, "Samsung": 3.99},
2010: {"Google": 9.89, "Nokia": 5.94, "Samsung": 4.45}
}
Expected output:
2008 [('Nokia', 3.45), ('Samsung', 10.98), ('Google', 10.98)]
2009 [('Google', 3.27), ('Samsung', 3.99), ('Nokia', 4.67)]
2010 [('Samsung', 4.45), ('Nokia', 5.94), ('Google', 9.89)]
Solution:
companies = {2008: {"Google": 10.98, "Nokia": 3.45, "Samsung": 10.98},
2009: {"Google": 3.27, "Nokia": 4.67, "Samsung": 3.99},
2010: {"Google": 9.89, "Nokia": 5.94, "Samsung": 4.45}
}
def user(item):
return item[1], 100-len(item[0])
for i in companies:
print(i, sorted(zip(companies[i].keys(), companies[i].values()), key = user)
How can I merge two Python dictionaries in a single expression?
->>> x = {'a': 1, 'b': 2}
->>> y = {'b': 3, 'c': 4}
->>> z1=zip(x,y)
->>> z1
<zip object at 0x02DEA5A8>
->>> z1=dict(zip(x,y))
->>> z1
{'a': 'c', 'b': 'b'} # WRONG
>>> z2=x.copy()
>>> z2.update(y)
>>> z2
{'a': 1, 'c': 4, 'b': 3}
->>> z3 = dict(x.items() | y.items())
->>> z3
{'a': 1, 'c': 4, 'b': 3}
->>> z4={**x,**y} # python above v.3.5
{'a': 1, 'c': 4, 'b': 3}
->>> z4
{'a': 1, 'c': 4, 'b': 3}
In these examples, Python merges dictionary keys in the order listed in the expression, overwriting duplicates from left to right.