Iterable Python

What’s Iterable?

An iterable is any Python object that can be looped over (iterated).

Common examples of iterables include:

Lists: [1, 2, 3, 4]
Tuples: (1, 2, 3, 4)
Strings: "hello"
Dictionaries: {"a": 1, "b": 2}

Map: Apply a function to many variables

map(function, *iterables) 

Example 1: Split an input and store all numbers in a list

Without map():

inputnum="3 4 5 2 2 9 8 5 2"

# => ["3","4","5"...]
inputnum=inputnum.split()

# => [3,4,5,...] 
for i in range(len(inputnum)):
    inputnum[i]=int(inputnum[i])

print(inputnum)

With map():

inputnum="3 4 5 2 2 9 8 5 2"

# => [3,4,5,...] 
inputnum= list(map(int, inputnum.split()))

print(inputnum)

Example 2: Cube of a list

def multiply(x):
    return x**3

inputlist = [3,5,7,8]
list(map(multiply,inputlist)) 

We could use lambda to define a small function

inputlist = [3,5,7,8]
list(map(lambda x:x**3,inputlist))

(search for “filter” if interested. It’s used for conditions with same syntax as map)

A readable approach: List comprehension

[what_you_want for item in iterable if condition]
inputlist = [3,5,7,8]
# Use map
list(map(lambda x:x**3,inputlist))

# Use List comprehension:
[x**3 for x in inputlist]

Dictionary Comprehension

Similar to list comprehension, but two variables are needed(keys and values).

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d={k:v for k, v in zip(keys, values)}
print(d)  # {'a': 1, 'b': 2, 'c': 3}

(zip function is used to make pairs, in the form of tuples).

Sorted “key”: Sort After Applying a function to each element in an iterable

Sometimes we want to sort a list after each element is applied to a function.

Example: y=(x-3)^2, which x has greatest y value.

x=[1,2.5,3,6,8]
sorted(x,key=lambda t: (t-3)**2)

“key” means that apply the following function to each element in list x.

It is a simplified version for this code:

x=[1,2.5,3,6,8]
y=[(t-3)**2 for t in x]
# or use map(), to calculate y list
y=list(map(lambda t: (t-3)**2,x))

# Then we sort y
sorted(y)

Groupby: group the elements with same key together

Example 1: group a dictionary

from itertools import groupby

students = [
    {"name": "Alice", "grade": "A"},
    {"name": "Bob", "grade": "B"},
    {"name": "Charlie", "grade": "A"},
    {"name": "David", "grade": "C"},
    {"name": "Eve", "grade": "B"},
]

# Sort the list by the "grade" key first
sorted_students = sorted(students, key=lambda x: x["grade"])

# Now, use groupby to group students by grade
{grade: list(group) for grade, group in groupby(sorted_students, key=lambda x: x["grade"])}

"""
   { 'A': [{'name': 'Alice', 'grade': 'A'}, {'name': 'Charlie', 'grade': 'A'}],
    'B': [{'name': 'Bob', 'grade': 'B'}, {'name': 'Eve', 'grade': 'B'}],
    'C': [{'name': 'David', 'grade': 'C'}]}
"""

We have to sort the list first before we group them. This is because groupby function only group continuous keys.

Example 2: group a tuple

Input:
1 SMS
7 SMS
5 BBC
9 Balabala
3 SMS

Output:
{'BBC': ['5'], 'Balabala': ['9'], 'SMS': ['1', '7', '3']}
groups=[tuple(input().split()) for i in range(5)]
dic={key:list(item[0] for item in group) for key, group in groupby(sorted(groups, key=lambda t: t[1]), key=lambda t: t[1])}
print(dic)

More itertools functions

Combinations

from itertools import combinations
comb = list(combinations([1, 2,7,8,9,4,6,4,3], 4))
print(comb) 
[(1, 2, 7, 8), (1, 2, 7, 9), (1, 2, 7, 4), (1, 2, 7, 6), (1, 2, 7, 4), (1, 2, 7, 3), (1, 2, 8, 9), (1, 2, 8, 4), (1, 2, 8, 6), (1, 2, 8, 4), (1, 2, 8, 3), (1, 2, 9, 4), (1, 2, 9, 6), (1, 2, 9, 4), (1, 2, 9, 3), (1, 2, 4, 6), (1, 2, 4, 4), (1, 2, 4, 3), (1, 2, 6, 4), (1, 2, 6, 3), (1, 2, 4, 3), (1, 7, 8, 9), (1, 7, 8, 4), (1, 7, 8, 6), (1, 7, 8, 4), (1, 7, 8, 3), (1, 7, 9, 4), (1, 7, 9, 6), (1, 7, 9, 4), (1, 7, 9, 3), (1, 7, 4, 6), (1, 7, 4, 4), (1, 7, 4, 3), (1, 7, 6, 4), (1, 7, 6, 3), (1, 7, 4, 3), (1, 8, 9, 4), (1, 8, 9, 6), (1, 8, 9, 4), (1, 8, 9, 3), (1, 8, 4, 6), (1, 8, 4, 4), (1, 8, 4, 3), (1, 8, 6, 4), (1, 8, 6, 3), (1, 8, 4, 3), (1, 9, 4, 6), (1, 9, 4, 4), (1, 9, 4, 3), (1, 9, 6, 4), (1, 9, 6, 3), (1, 9, 4, 3), (1, 4, 6, 4), (1, 4, 6, 3), (1, 4, 4, 3), (1, 6, 4, 3), (2, 7, 8, 9), (2, 7, 8, 4), (2, 7, 8, 6), (2, 7, 8, 4), (2, 7, 8, 3), (2, 7, 9, 4), (2, 7, 9, 6), (2, 7, 9, 4), (2, 7, 9, 3), (2, 7, 4, 6), (2, 7, 4, 4), (2, 7, 4, 3), (2, 7, 6, 4), (2, 7, 6, 3), (2, 7, 4, 3), (2, 8, 9, 4), (2, 8, 9, 6), (2, 8, 9, 4), (2, 8, 9, 3), (2, 8, 4, 6), (2, 8, 4, 4), (2, 8, 4, 3), (2, 8, 6, 4), (2, 8, 6, 3), (2, 8, 4, 3), (2, 9, 4, 6), (2, 9, 4, 4), (2, 9, 4, 3), (2, 9, 6, 4), (2, 9, 6, 3), (2, 9, 4, 3), (2, 4, 6, 4), (2, 4, 6, 3), (2, 4, 4, 3), (2, 6, 4, 3), (7, 8, 9, 4), (7, 8, 9, 6), (7, 8, 9, 4), (7, 8, 9, 3), (7, 8, 4, 6), (7, 8, 4, 4), (7, 8, 4, 3), (7, 8, 6, 4), (7, 8, 6, 3), (7, 8, 4, 3), (7, 9, 4, 6), (7, 9, 4, 4), (7, 9, 4, 3), (7, 9, 6, 4), (7, 9, 6, 3), (7, 9, 4, 3), (7, 4, 6, 4), (7, 4, 6, 3), (7, 4, 4, 3), (7, 6, 4, 3), (8, 9, 4, 6), (8, 9, 4, 4), (8, 9, 4, 3), (8, 9, 6, 4), (8, 9, 6, 3), (8, 9, 4, 3), (8, 4, 6, 4), (8, 4, 6, 3), (8, 4, 4, 3), (8, 6, 4, 3), (9, 4, 6, 4), (9, 4, 6, 3), (9, 4, 4, 3), (9, 6, 4, 3), (4, 6, 4, 3)]

After listing all conditions, we can use “for” loop to go though each condition.

 

Cycle and Islice

from itertools import cycle, islice

cyclic = cycle([1, 2, 3])
first_six = list(islice(cyclic, 6))
print(first_six)  # [1, 2, 3, 1, 2, 3]

 

Comments

Popular Posts