0% found this document useful (0 votes)
5 views

Python_I_G_C

The document provides an overview of Python's iterators, generators, and comprehensions. It explains how iterators allow for sequential access to elements in collections, while generators are a type of iterator that yield values one at a time using the 'yield' keyword. Additionally, it covers comprehensions as concise methods for creating collections like lists, dictionaries, and sets.

Uploaded by

sadikjr330
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python_I_G_C

The document provides an overview of Python's iterators, generators, and comprehensions. It explains how iterators allow for sequential access to elements in collections, while generators are a type of iterator that yield values one at a time using the 'yield' keyword. Additionally, it covers comprehensions as concise methods for creating collections like lists, dictionaries, and sets.

Uploaded by

sadikjr330
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Python

Iterators, Generators, Comprehensions

[email protected] 1
Iterators:
• An iterator is an object that represents a stream of data.

[email protected] 2
Iterators:
• An iterator is an object that represents a stream of data.
• It allows you to loop over a collection (like a list, tuple, or dictionary)
one item at a time.

[email protected] 3
Iterators:
• An iterator is an object that represents a stream of data.
• It allows you to loop over a collection (like a list, tuple, or dictionary)
one item at a time.
• You can create an iterator from an iterable using the iter() function
and then retrieve elements with the next() function.

[email protected] 4
Iterators:
• An iterator is an object that represents a stream of data.
• It allows you to loop over a collection (like a list, tuple, or dictionary)
one item at a time.
• You can create an iterator from an iterable using the iter() function
and then retrieve elements with the next() function.
• When there are no more items to be returned, it raises a
StopIteration exception.

[email protected] 5
Iterators:
• An iterator is an object that represents a stream of data.
• It allows you to loop over a collection (like a list, tuple, or dictionary)
one item at a time.
• You can create an iterator from an iterable using the iter() function
and then retrieve elements with the next() function.
• When there are no more items to be returned, it raises a
StopIteration exception.
• You can also use a for loop to iterate over an iterator.

[email protected] 6
Example:
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))

[email protected] 7
Example:
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator)) # 1
print(next(my_iterator)) # 2
print(next(my_iterator)) # 3
# Raises StopIteration: print(next(my_iterator))

[email protected] 8
Iterators
• An iterator is an object that implements two methods, __iter__() and
__next__(), to allow iteration over a collection of items. Here's a
breakdown of how iterators work:
• __iter__(): This method returns the iterator object itself. It is typically
used to initialize the iterator, such as setting the current position to
the beginning of the collection.

• __next__(): This method retrieves the next item from the collection. If
there are no more items, it raises a StopIteration exception.

[email protected] 9
class MyIterator:
def __init__(self, collection):
self.collection = collection
self.index = 0

def __iter__(self):
return self

def __next__(self):
if self.index < len(self.collection):
result = self.collection[self.index]
self.index += 1
return result
raise StopIteration

my_list = [1, 2, 3]
my_iterator = MyIterator(my_list)
for item in my_iterator:
print(item)
[email protected] 10
class MyIterator:
def __init__(self, collection):
self.collection = collection
self.index = 0

def __iter__(self):
return self

def __next__(self):
if self.index < len(self.collection):
result = self.collection[self.index]
self.index += 1
return result
raise StopIteration

my_list = [1, 2, 3]
my_iterator = MyIterator(my_list)
for item in my_iterator:
print(item) # 1, 2, 3
[email protected] 11
Generators:
• Generators are a type of iterator, but they are created using a special
function called a generator function or generator expression.

[email protected] 12
Generators:
• Generators are a type of iterator, but they are created using a special
function called a generator function or generator expression.
• They use the yield keyword to produce a series of values one at a
time, and they maintain their state between calls.

[email protected] 13
Generators:
• Generators are a type of iterator, but they are created using a special
function called a generator function or generator expression.
• They use the yield keyword to produce a series of values one at a
time, and they maintain their state between calls.
• Generators are memory-efficient because they don't generate all the
values at once but only when requested.

[email protected] 14
Generators:
• Generators are a type of iterator, but they are created using a special
function called a generator function or generator expression.
• They use the yield keyword to produce a series of values one at a
time, and they maintain their state between calls.
• Generators are memory-efficient because they don't generate all the
values at once but only when requested.
• You can iterate over a generator using a for loop or by calling next().

[email protected] 15
Example:
def my_generator():
yield 1
yield 2
yield 3

gen = my_generator()
for item in gen:
print(item)

[email protected] 16
Example:
def my_generator():
yield 1
yield 2
yield 3

gen = my_generator()
for item in gen:
print(item) # 1, 2, 3

[email protected] 17
Generators are a more concise and convenient way to create iterators. They
use the yield keyword, which allows a function to yield values one at a time
without losing its state. When you call a generator function, it doesn't execute
the function immediately; instead, it returns a generator object. When you
iterate over the generator or use next(), the function's execution is paused at
the yield statement until the next value is requested.

[email protected] 18
def count_up_to(n):
i=1
while i <= n:
yield i
i += 1

gen = count_up_to(3)
for value in gen:
print(value)

[email protected] 19
def count_up_to(n):
i=1
while i <= n:
yield i
i += 1

gen = count_up_to(3)
for value in gen:
print(value) # 1, 2, 3

[email protected] 20
Comprehensions:
• Comprehensions are concise ways to create collections, such as lists,
dictionaries, and sets, using a single line of code.
• They provide a more readable and Pythonic way to generate data
collections based on existing iterables.
• There are three types of comprehensions in Python:
• List comprehensions: Create lists.
• Dictionary comprehensions: Create dictionaries.
• Set comprehensions: Create sets.

[email protected] 21
Examples: List comprehension
squares = [x**2 for x in range(1, 5)]

[email protected] 22
Examples: List comprehension
squares = [x**2 for x in range(1, 5)]
# squares is [1, 4, 9, 16]

[email protected] 23
Examples: Dictionary comprehension
squares_dict = {x: x**2 for x in range(1, 5)}

[email protected] 24
Examples: Dictionary comprehension
squares_dict = {x: x**2 for x in range(1, 5)}
# squares_dict is {1: 1, 2: 4, 3: 9, 4: 16}

[email protected] 25
Set comprehension:

Examples: Set comprehension


unique_squares = {x**2 for x in range(1, 5)}

[email protected] 26
Set comprehension:

Examples: Set comprehension


unique_squares = {x**2 for x in range(1, 5)}
# unique_squares is {1, 4, 9, 16}

[email protected] 27
Dictionary Functions and Methods:
cmp() (Python 2.x only):
1. Compares two dictionaries and returns:
1. 0 if they are equal
2. 1 if the first dictionary is greater
3. -1 if the second dictionary is greater

[email protected] 28
Dictionary Functions and Methods:
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 1, 'b': 3}
result = cmp(dict1, dict2)

[email protected] 29
Ex.
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 1, 'b': 3}
result = cmp(dict1, dict2) # Compares dict1 and dict2
# Result: -1 (dict2 is considered greater)

[email protected] 30
len():
• Returns the number of key-value pairs in a dictionary.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
length = len(my_dict)

[email protected] 31
len():
• Returns the number of key-value pairs in a dictionary.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
length = len(my_dict)
# Length: 3

[email protected] 32
clear():
• Removes all key-value pairs from the dictionary, making it empty.
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()

[email protected] 33
clear():
• Removes all key-value pairs from the dictionary, making it empty.
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear() # Clears the dictionary
# my_dict is now an empty dictionary: {}

[email protected] 34
get(key, default):
• Returns the value associated with a key if it exists in the dictionary.

[email protected] 35
get(key, default):
• Returns the value associated with a key if it exists in the dictionary.
• If the key is not found, it returns the default value (or None if not
specified).

[email protected] 36
get(key, default):
• Returns the value associated with a key if it exists in the dictionary.
• If the key is not found, it returns the default value (or None if not
specified).
my_dict = {'name’: Ravi', 'age’: 30}
age = my_dict.get('age', 0)

[email protected] 37
get(key, default):
• Returns the value associated with a key if it exists in the dictionary.
• If the key is not found, it returns the default value (or None if not
specified).
my_dict = {'name': 'Alice', 'age': 30}
age = my_dict.get('age', 0) # Get age with default value 0 if not found
# Age: 30

[email protected] 38
items():
• Returns a list of tuples containing key-value pairs in the dictionary.

[email protected] 39
items():
• Returns a list of tuples containing key-value pairs in the dictionary.
my_dict = {'name’: Ravi', 'age': 30}
items = my_dict.items()

[email protected] 40
items():
• Returns a list of tuples containing key-value pairs in the dictionary.
my_dict = {'name’: Ravi', 'age': 30}
items = my_dict.items() # Get list of key-value pairs
# Items: [('name’, Ravi'), ('age', 30)]

[email protected] 41
keys():
• Returns a list of keys in the dictionary.

[email protected] 42
keys():
• Returns a list of keys in the dictionary.
my_dict = {'name’: Ravi', 'age': 30}
keys = my_dict.keys()

[email protected] 43
keys():
• Returns a list of keys in the dictionary.
my_dict = {'name’: Ravi', 'age': 30}
keys = my_dict.keys() # Get list of keys
# Keys: ['name', 'age']

[email protected] 44
update(other_dict):
• Merges the key-value pairs from another dictionary (other_dict) into
the current dictionary.
• If a key already exists, its value is updated; otherwise, a new key-value
pair is added.

[email protected] 45
update(other_dict):
• Merges the key-value pairs from another dictionary (other_dict) into
the current dictionary.
• If a key already exists, its value is updated; otherwise, a new key-value
pair is added.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2

[email protected] 46
update(other_dict):
• Merges the key-value pairs from another dictionary (other_dict) into
the current dictionary.
• If a key already exists, its value is updated; otherwise, a new key-value
pair is added.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2) # Merges dict2 into dict1
# dict1 is now {'a': 1, 'b': 3, 'c': 4}

[email protected] 47
values():
• Returns a list of values in the dictionary.

[email protected] 48
values():
• Returns a list of values in the dictionary.
my_dict = {'name': ‘Ravi', 'age': 30}
values = my_dict.values

[email protected] 49
values():
• Returns a list of values in the dictionary.
my_dict = {'name': ‘Ravi', 'age': 30}
values = my_dict.values() # Get list of values
# Values: [‘Ravi', 30]

[email protected] 50
pop(key, default):
• Removes and returns the value associated with a key.
• If the key is not found, it returns the default value (or raises a
KeyError if not specified).

[email protected] 51
pop(key, default):
• Removes and returns the value associated with a key.
• If the key is not found, it returns the default value (or raises a
KeyError if not specified).
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b', 0)

[email protected] 52
pop(key, default):
• Removes and returns the value associated with a key.
• If the key is not found, it returns the default value (or raises a KeyError if
not specified).
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b', 0) # Remove 'b' with default value 0 if not found
# Value: 2

[email protected] 53
fromkeys(seq, value):
• Creates a new dictionary with keys from the sequence seq and all
values set to a specified value.

[email protected] 54
fromkeys(seq, value):
• Creates a new dictionary with keys from the sequence seq and all
values set to a specified value.
keys = ['a', 'b', 'c']
default_value = 0
new_dict = dict.fromkeys(keys, default_value)

[email protected] 55
fromkeys(seq, value):
• Creates a new dictionary with keys from the sequence seq and all
values set to a specified value.
keys = ['a', 'b', 'c']
default_value = 0
new_dict = dict.fromkeys(keys, default_value)
# New Dictionary: {'a': 0, 'b': 0, 'c': 0}

[email protected] 56
dict():
• Constructs a dictionary from an iterable of key-value pairs (tuples).

[email protected] 57
dict():
• Constructs a dictionary from an iterable of key-value pairs (tuples).
key_value_pairs = [('a', 1), ('b', 2), ('c', 3)]
new_dict = dict(key_value_pairs)

[email protected] 58
dict():
• Constructs a dictionary from an iterable of key-value pairs (tuples).
key_value_pairs = [('a', 1), ('b', 2), ('c', 3)]
new_dict = dict(key_value_pairs)
# New Dictionary: {'a': 1, 'b': 2, 'c': 3}

[email protected] 59

You might also like