list
Loops in Python
Loops are fundamental in programming for repeating code blocks. Python supports various loop types with specific applications.
16. Loops
Parameter Details
- boolean expression: An expression evaluated in a boolean context (e.g., x < 10).
- variable: The name of the current element from the iterable.
- iterable: Any object that supports iteration.
Loops are essential for repeating sections of code. Each repetition is called an iteration.
16.1: Break and Continue in Loops
Break Statement
The break statement terminates the loop immediately when executed.
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1
- The loop condition is not evaluated after
break. breakis only allowed inside loops.- Example:
0
1
2
3
4
Breaking from loop
break can also be used in for loops.
for i in (0, 1, 2, 3, 4):
print(i)
if i == 2:
break
Output:
0
1
2
Else Clause in Loops
If a loop terminates due to a break statement, the else clause (if present) is not executed.
Continue Statement
The continue statement skips the rest of the current iteration and proceeds to the next.
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
Output:
0
1
3
5
Nested Loops
break and continue only affect the innermost loop.
while True:
for i in range(1,5):
if i == 2:
break # Breaks only the inner loop
To break out of multiple loops, consider refactoring the code into a function and using return.
Use Return From Within a Function as a Break
return exits a function, halting further code execution within the function.
def break_loop():
for i in range(1, 5):
if (i == 2):
return(i)
print(i)
return(5)
For nested loops, return breaks all loops.
def break_all():
for j in range(1, 5):
for i in range(1,4):
if i*j == 6:
return(i)
print(i*j)
Output:
1
2
3
4
2
4
16.2: For loops
for loops iterate over a collection of items.
for i in [0, 1, 2, 3, 4]:
print(i)
Output:
0
1
2
3
4
range() generates a series of numbers, which can be used in for loops.
for i in range(5):
print(i)
Iterable Objects and Iterators
for loops can iterate over any iterable object, defining either __getitem__ or __iter__ methods. The __iter__ function returns an iterator with a next function to access elements.
16.3: Iterating Over Lists
for x in ['one', 'two', 'three', 'four']:
print(x)
Output:
one
two
three
four
Using range():
for x in range(1, 6):
print(x)
Output:
1
2
3
4
5
Enumerate
The enumerate function provides both index and value.
for index, item in enumerate(['one', 'two', 'three', 'four']):
print(index, ' ::', item)
Output:
(0, ' ::', 'one')
(1, ' ::', 'two')
(2, ' ::', 'three')
(3, ' ::', 'four')
Value Manipulation with Map and Lambda
Apply a lambda function to each list element using map.
x = map(lambda e : e.upper(), ['one', 'two', 'three', 'four'])
print(list(x))
Output:
['ONE', 'TWO', 'THREE', 'FOUR']
16.4: Loops with an "Else" Clause
for and while loops can have an else clause that executes after the loop completes normally (i.e., not terminated by break or an exception).
for i in range(3):
print(i)
else:
print('done')
Output:
0
1
2
done
The else clause does not execute if the loop is terminated by a break.
for i in range(2):
print(i)
if i == 1:
break
else:
print('done')
Output:
0
1
The else clause can be interpreted as "if not break" or "if not found".
16.5: The Pass Statement
pass is a null statement used where syntax requires a statement but no action is needed.
for x in range(10):
pass # No action
pass can also be used in while loops, selections, and function definitions.
while x == y:
pass
16.6: Iterating Over Dictionaries
Given the dictionary:
d = {"a": 1, "b": 2, "c": 3}
Iterating through keys:
for key in d:
print(key)
Output:
a
b
c
Iterating Through Values:
for value in d.values():
print(value)
Output:
1
2
3
Iterating Through Keys and Values
for key, value in d.items():
print(key, "::", value)
Output:
a :: 1
b :: 2
c :: 3
In Python 2, .keys(), .values(), and .items() return lists; .iterkeys(), .itervalues(), and .iteritems() are generators.
In Python 3, the order of items printed is not guaranteed.
16.7: The "Half Loop" Do-While
Python lacks a direct do-while construct, but it can be emulated using while True and break.
a = 10
while True:
a = a-1
print(a)
if a<7:
break
print('Done. ')
Output:
9
8
7
6
Done.
16.8: Looping and Unpacking
Looping over a list of tuples can be simplified using unpacking.
collection = [('a', 'b', 'c'), ('x', 'y', 'z'), ('1', '2', '3')]
for i1, i2, i3 in collection:
# logic
pass
16.9: Iterating Different Portions of a List with Different Step Size
Use Python's indexing and range for custom iteration.
lst = ['alpha', 'bravo', 'charlie', 'delta', 'echo']
Iteration over the Whole List
for s in lst:
print(s[:1]) # Print the first letter
Output:
a
b
c
d
e
Enumerate
for idx, s in enumerate(lst):
print("%s has an index of %d" % (s, idx))
Output:
alpha has an index of 0
bravo has an index of 1
charlie has an index of 2
delta has an index of 3
echo has an index of 4
Iterate Over Sub-List
for i in range(2,4):
print("lst at %d contains %s" % (i, lst[i]))
Output:
lst at 2 contains charlie
lst at 3 contains delta
Slicing
for s in lst[1::2]:
print(s)
Output:
bravo
delta
16.10: While Loop
A while loop executes as long as the condition is truthy.
i = 0
while i < 4:
# loop statements
i = i + 1
while loops are useful for waiting for a condition to be met.
myObject = anObject()
while myObject.isNotReady():
myObject.tryToGetReady()
while loops can run indefinitely.
import cmath
complex_num = cmath.sqrt(-1)
while complex_num:
print(complex_num) # Prints 1j forever
Infinite loops require a break, return, or exception to terminate.
while True:
print "Infinite loop"
Arrays in Python
Arrays in Python are similar to lists but are constrained to elements of the same data type.
17: Arrays
Parameter Details
- b: Signed integer of size 1 byte
- B: Unsigned integer of size 1 byte
- c: Character of size 1 byte
- u: Unicode character of size 2 bytes
- h: Signed integer of size 2 bytes
- H: Unsigned integer of size 2 bytes
- i: Signed integer of size 2 bytes
- I: Unsigned integer of size 2 bytes
- w: Unicode character of size 4 bytes
- l: Signed integer of size 4 bytes
- L: Unsigned integer of size 4 bytes
- f: Floating point of size 4 bytes
- d: Floating point of size 8 bytes
17.1: Access Individual Elements Through Indexes
Arrays are zero-indexed.
from array import *
my_array = array('i', [1,2,3,4,5])
print(my_array[1]) # 2
print(my_array[2]) # 3
print(my_array[0]) # 1
17.2: Basic Introduction to Arrays
Arrays store values of the same data type, unlike lists which can contain mixed types.
from array import *
arrayIdentifierName = array(typecode, [Initializers])
my_array = array('i', [1,2,3,4])
Typecodes define the array's data type.
from array import *
my_array = array('i', [1,2,3,4,5])
for i in my_array:
print(i)
Output:
1
2
3
4
5
17.3: Append Any Value to the Array Using Append() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_array.append(6) # array('i', [1, 2, 3, 4, 5, 6])
17.4: Insert Value in an Array Using Insert() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_array.insert(0,0) #array('i', [0, 1, 2, 3, 4, 5])
17.5: Extend Python Array Using Extend() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_extnd_array = array('i', [7,8,9,10])
my_array.extend(my_extnd_array) # array('i', [1, 2, 3, 4, 5, 7, 8, 9, 10])
17.6: Add Items From List Into Array Using Fromlist() Method
from array import *
my_array = array('i', [1,2,3,4,5])
c=[11,12,13]
my_array.fromlist(c)
# array('i', [1, 2, 3, 4, 5, 11, 12, 13])
17.7: Remove Any Array Element Using Remove() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_array.remove(4)
# array('i', [1, 2, 3, 5])
17.8: Remove Last Array Element Using Pop() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_array.pop()
# array('i', [1, 2, 3, 4])
17.9: Fetch Any Element Through Its Index Using Index() Method
from array import *
my_array = array('i', [1,2,3,4,5])
print(my_array.index(5)) # 4
17.10: Reverse a Python Array Using Reverse() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_array.reverse()
# array('i', [5, 4, 3, 2, 1])
17.11: Get Array Buffer Information Through Buffer_Info() Method
from array import *
my_array = array('i', [1,2,3,4,5])
my_array.buffer_info()
Returns (address, length).
17.12: Check for Number of Occurrences of an Element Using Count() Method
from array import *
my_array = array('i', [1,2,3,3,5])
my_array.count(3) # 2
17.13: Convert Array to String Using Tostring() Method
from array import *
my_char_array = array('c', ['g', 'e', 'e', 'k'])
print(my_char_array.tostring())
17.14: Convert Array to a Python List With Same Elements Using Tolist() Method
from array import *
my_array = array('i', [1,2,3,4,5])
c = my_array.tolist()
# [1, 2, 3, 4, 5]
17.15: Append a String to Char Array Using Fromstring() Method
from array import *
my_char_array = array('c', ['g', 'e', 'e', 'k'])
my_char_array.fromstring("stuff")
print(my_char_array)
# array('c', 'geekstuff')
Multidimensional Arrays
Multidimensional arrays can be represented as lists of lists.
18: Multidimensional arrays
18.1: Lists in Lists
2D arrays can be visualized as lists of lists.
lst=[[1,2,3],[4,5,6],[7,8,9]]
print (lst[0]) #output: [1, 2, 3]
print (lst[1]) #output: [4, 5, 6]
print (lst[2]) #output: [7, 8, 9]
print (lst[0][0]) #output: 1
print (lst[0][1]) #output: 2
lst[0]=[10,11,12]
lst[1][2]=15
18.2: Lists in Lists in Lists In..
Higher dimensional arrays can be created by nesting lists.
3D array example:
[[[111,112,113],[121,122,123],[131,132,133]],
[[211,212,213],[221,222,223],[231,232,233]],
[[311,312,313],[321,322,323],[331,332,333]]]
Accessing elements is similar to 2D arrays.
Dictionaries
Dictionaries are key-value stores that allow fast lookups based on keys.
19: Dictionary
Parameter Details
- key: The key to lookup
- value: The value to set or return
19.1: Introduction to Dictionary
A dictionary is a key-value store (mapping) in Python.
Creating a Dict
d = {} # empty dict
d = {'key': 'value'} # dict with initial values
Python 3.5+:
d = {**otherdict}
d = {**otherdict, **yetanotherdict}
d = {k:v for k,v in [('key', 'value',)]}
d = dict() # empty dict
d = dict(key='value') # explicit keyword arguments
d = dict([('key', 'value')]) # passing in a list of key/value pairs
d = dict(**otherdict) # make a shallow copy of another dict
Modifying a Dict
d['newkey'] = 42
d['new_list'] = [1, 2, 3]
d['new_dict'] = {'nested_dict': 1}
del d['newkey']
19.2: Avoiding KeyError Exceptions
Accessing a non-existent key raises a KeyError.
Dict.Get Method
Use dict.get to specify a default value for absent keys.
value = mydict.get(key, default_value)
Dict.Setdefault Method
Use dict.setdefault to also store the key-value pair.
mydict = {}
print(mydict.get("foo", "bar")) # bar
print(mydict.setdefault("foo", "bar")) # bar
print(mydict) # {'foo': 'bar'}
Try-Except Block
try:
value = mydict[key]
except KeyError:
value = default_value
Check Key Existence
if key in mydict:
value = mydict[key]
else:
value = default_value
Collections.Defaultdict
A subclass of dict with a default_factory.
19.3: Iterating Over a Dictionary
Iterating over a dictionary traverses its keys.
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key, d[key])
The items() method loops over both key and value (Python 3).
for key, value in d.items():
print(key, value)
values() iterates only over the values.
19.4: Dictionary with Default Values
From collections import defaultdict.
from collections import defaultdict
d = defaultdict(int)
d['key'] # 0
d = defaultdict(lambda: 'empty')
d['key'] # 'empty'
dict.setdefault() can also create a default.
19.5: Merging Dictionaries
Python 3.5+:
fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"}
dog = {'name': "Clifford", 'hands': "paws", 'color': "red"}
fishdog = {**fish, **dog} # {'hands': 'paws', 'color': 'red', 'name': 'Clifford', 'special': 'gills'}
Duplicate keys map to their lattermost value.
19.6: Accessing Keys and Values
mydict = {
'a': '1',
'b': '2'
}
print(mydict.keys()) # Python2: ['a', 'b'], Python3: dict_keys(['b', 'a'])
print(mydict.values()) # Python2: ['1', '2'], Python3: dict_values(['2', '1'])
print(mydict.items()) # Python2: [('a', '1'), ('b', '2')], Python3: dict_items([('b', '2'), ('a', '1')])
Keys, values, and items have no sort order.
19.7: Accessing Values of a Dictionary
dictionary = {"Hello": 1234, "World": 5678}
print(dictionary["Hello"])
Use dictionary.get to avoid KeyError.
19.8: Creating a Dictionary
Rules for Creating a Dictionary
- Keys must be unique.
- Keys must be hashable.
- No particular order for keys.
stock = {'eggs': 5, 'milk': 2}
dictionary = {}
dictionary['eggs'] = 5
dictionary['milk'] = 2
mydict = {'a': [1, 2, 3], 'b': ['one', 'two', 'three']}
mydict['a'].append(4)
mydict['b'].append('four')
dictionary = dict(iterables)
dictionary = dict(eggs=5, milk=2)
dictionary = dict.fromkeys((milk, eggs))
dictionary = dict.fromkeys((milk, eggs), (2, 5))
19.9: Creating an Ordered Dictionary
Use OrderedDict from the collections module.
from collections import OrderedDict
d = OrderedDict()
d['first'] = 1
d['second'] = 2
d['third'] = 3
d['last'] = 4
for key in d:
print(key, d[key])
19.10: Unpacking Dictionaries Using The ** Operator
Deliver key-value pairs into a function's arguments or merge dictionaries.
def parrot(voltage, state, action):
print("This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.", end=' ')
print("E's", state, "!")
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
Python 3.5+:
fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"}
dog = {'name': "Clifford", 'hands': "paws", 'color': "red"}
fishdog = {**fish, **dog}
19.11: The Trailing Comma
Like lists and tuples, you can include a trailing comma in your dictionary.
role = {"By day": "A typical programmer", "By night": "Still a typical programmer", }
19.12: The Dict() Constructor
The dict() constructor creates dictionaries.
dict(a=1, b=2, c=3)
dict([('d', 4), ('e', 5), ('f', 6)])
dict([('a', 1)], b=2, c=3)
dict({'a': 1, 'b': 2}, c=3)
19.13: Dictionaries Example
car = {}
car["wheels"] = 4
car["color"] = "Red"
car["model"] = "Corvette"
print "Little " + car["color"] + " " + car["model"] + "!"
car = {"wheels": 4, "color": "Red", "model": "Corvette"}
for key in car:
print key + ": " + car[key]
19.14: All Combinations of Dictionary Values
Generate all combinations of dictionary values using itertools.product.
import itertools
options = {
"x": ["a", "b"],
"y": [10, 20, 30]
}
keys = options.keys()
values = (options[key] for key in keys)
combinations = [dict(zip(keys, combination)) for combination in itertools.product(*values)]
print combinations
Lists
The Python List is a general, mutable, and sequence data structure.
20: List
List Methods and Supported Operators
a = [1, 2, 3, 4, 5]
Append(Value)
Appends a new element to the end of the list.
a.append(6)
a.append(7)
a.append(7)
b = [8, 9]
a.append(b)
a.append("hello world")
Extend(Enumerable)
Extends the list by appending elements from another enumerable.
a.extend(b)
a.extend(range(3))
a = [1, 2, 3, 4, 5, 6] + [7, 7] + b
Index(Value, [Startindex])
Gets the index of the first occurrence of the input value.
Raises a ValueError exception if the input value is not in the list.
a.index(7)
a.index(7, 7)
Insert(Index, Value)
Inserts value just before the specified index.
a.insert(0, 0)
a.insert(2, 5)
Pop([Index])
Removes and returns the item at index. With no argument, it removes and returns the last element.
a.pop(2)
a.pop()
Remove(Value)
Removes the first occurrence of the specified value. Raises a ValueError if not found.
a.remove(0)
Reverse()
Reverses the list in-place and returns None.
a.reverse()
Count(Value)
Counts the number of occurrences of some value in the list.
a.count(7)
Sort()
Sorts the list in numerical and lexicographical order and returns None.
a.sort()
a.sort(reverse=True)
Clear()
Removes all items from the list.
a.clear()
Replication
Multiplying an existing list by an integer produces a larger list consisting of that many copies of the original.
b = ["blah"] * 3
b = [1, 3, 5] * 5
Element Deletion
a = list(range(10))
del a[::2]
del a[-1]
del a[:]
Copying
b = a
a.append(6)
new_list = old_list[:]
new_list = list(old_list)
import copy
new_list = copy.copy(old_list)
new_list = copy.deepcopy(old_list)
Copy() (Python 3.x)
Returns a shallow copy of the list.
aa = a.copy()
20.2: Accessing List Values
lst = [1, 2, 3, 4]
lst[0] # 1
lst[-1] # 4
lst[1:] # [2, 3, 4]
lst[:3] # [1, 2, 3]
lst[::2] # [1, 3]
lst[::-1] # [4, 3, 2, 1]
lst[-1:0:-1] # [4, 3, 2]
lst[5:8] # []
lst[1:10] # [2, 3, 4]
lst[::-1] # [4, 3, 2, 1]
Advanced Slicing
data = 'chandan purohit 22 2000'
name_slice = slice(0,19)
age_slice = slice(19,21)
salary_slice = slice(22,None)
print(data[name_slice])
print(data[age_slice])
print(data[salary_slice])
20.3: Checking If List Is Empty
lst = []
if not lst:
print("list is empty")
20.4: Iterating Over a List
my_list = ['foo', 'bar', 'baz']
for item in my_list:
print(item)
for (index, item) in enumerate(my_list):
print('The item in position {} is: {}'.format(index, item))
for i in range(0,len(my_list)):
print(my_list[i])