Zipped = list(list(x) for x in zip(l1, l2)) The first method uses a generator expression and converts the resulting iterable to a list using the list() constructor. This is efficient but not the most concise way of accomplishing this task. Method 2: List ComprehensionĪ better way is to use list comprehension which is like a generator expression but it creates a list directly without the need to convert an iterable to a list (as in Method 1). l1 = Ĭoders who don’t like list comprehension and generator expressions (or, who don’t understand these beautiful Python features) often use a simple for loop. In the loop body, you convert each tuple in the zip object to a list and append this list to the nested list zipped. This method is readable but less concise. This method is often used by coders who know neither the zip() method, nor list comprehension, nor generator expressions: loop over all indices and append a new list obtained by grouping the i-th elements to the list. However, this method is least Pythonic, lengthy, and it works only for equally-sized lists.Įxercise: What happens if the first list has more elements than the second list? Method 5: Zip() + Map() + List()Ī functional way of solving this problem is the map() function that applies a function to each element of an iterable and returns a map object. You can pass the list() constructor to the map() function to convert each tuple in the zip object to a list. You can then convert the map object to a list. I don’t recommend this method because functional programming may be difficult to understand for many beginner coders. Guido van Rossum, the creator of Python, disliked functional programming as well. The most Pythonic way to create a list of lists by zipping together multiple lists is the list comprehension statement. List comprehension is fast, efficient, concise, and readable. You can also extend it to the general case by adding more lists to the zip function. The zip() function is also robust against lists of different lengths. In this case, the elements up to the maximal index of the shortest list are zipped. For example, the functions ifilter(), imap(), and izip() are directly. Where to Go From Here?Ĭoders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. Python 2.2 introduced simple generators to Python language, and reconceived. To become more successful in coding, solve more real problems for real people. You build high-value coding skills by working on practical coding projects!ĭo you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people? After all, what’s the use of learning theory that nobody ever needs? That’s how you polish the skills you really need in practice.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |