2.3.4. Join Iterables

2.3.4.1. join method: Turn an Iterable into a Python String

If you want to turn an iterable into a string, use join().

In the code below, I join elements in the list fruits using “, “.

fruits = ['apples', 'oranges', 'grapes']

fruits_str = ', '.join(fruits)

print(f"Today, I need to get some {fruits_str} in the grocery store")
Today, I need to get some apples, oranges, grapes in the grocery store

2.3.4.2. Zip: Associate Elements from Two Iterators based on the Order

If you want to associate elements from two iterators based on the order, combine list and zip.

nums = [1, 2, 3, 4]
string = "abcd"
combinations = list(zip(nums, string))
combinations
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

2.3.4.3. Zip Function: Create Pairs of Elements from Two Lists in Python

If you want to create pairs of elements from two lists, use zip. zip() function takes iterables and aggregates them in a tuple.

You can also unzip the list of tuples by using zip(*list_of_tuples).

nums = [1, 2, 3, 4]
chars = ['a', 'b', 'c', 'd']

comb = list(zip(nums, chars))
comb 
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
nums_2, chars_2 = zip(*comb)
nums_2, chars_2
((1, 2, 3, 4), ('a', 'b', 'c', 'd'))