Python lists are data structures used to store and change items. If you’re just learning Python or want to learn some neat tricks when using lists, this post is for you! The documentation on python lists can be found here.
1. Create a dictionary from two lists:
Dictionaries, which are indexed by keys, can be created using two lists: a list of the keys and a list of the values.
output: {‘key_1’: 1, ‘key_2’: 2, ‘key_3’: 3}
2. Partition a list into a list of lists:
We can split a list into groups by partitioning the list into lists of n elements. Given a list, and a number to group by, we can use the range function to divide the list. We can then append items from the list for every n items.
output: [[1, 2], [3, 4], [5, 6], [7]]
3. Partition a list into a list of tuples:
Tuples are another data structure in Python that are immutable and cannot be changed. Just as we can partition a list into a list of lists, we can partition a list into a list of tuples.
Output: [(1, 3), (2, 4), (6, 5)]
4. Flatten a list of lists into a single list:
In Python, we can take a list of lists and flatten it into a list of all of the elements. We can create a function that takes in a list of lists, and a new, empty list, and outputs the list of lists by appending each item to the new list.
5. Copy a list and make changes
In Python, if we set a list equal to another list, such that a = b, and make changes to a, the changes will apply to b as well. In order to copy a list, and change only one list and not both, we need to use the .copy() method.
6. Element-wise addition of two lists
In Python, if we add two lists together, we get a list that combines the elements from both lists into a single list.
a + b = [a1, a2, a3, b1, b2, b3]
In order to add the lists element-wise, we need to iterate over both lists. A for loop can be a great way to iterate over a list. However, if we create two for loops to try to iterate over both lists we get the following:
This will return all possible combinations of x + y and will not provide the solution we need.
Rather, we need to use the zip function, which aggregates the elements of the lists we are iterating over.
In order to store the results of the element-wise addition, we can use the method .append() to add the results to a new list.
Take a look at the solution below. ⬇️
output[7, 9, 11, 13, 15]
Top comments (0)