Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Join List Pairs

#1
Python Join List Pairs

Given a list of strings. Join the first with the second string, the second with the third, and so on. The one-liner [lst[i] + lst[i+1] for i in range(0, len(lst), 2)] solves the problem by using the range function to iterate over every other index i=0, 2, 4, 5, ... to concatenate the i-th and the i+1-th elements in a list comprehension expression with lst[i] + lst[i+1].

You may already know the normal join function in Python:

Intro: Python Join


Problem: Given a list of elements. How to join the elements by concatenating all elements in the list?

Example: You want to convert list ['learn ', 'python ', 'fast'] to the string 'learn python fast'.

Quick Solution: to convert a list of strings to a string, do the following.

  • Call the ''.join(list) method on the empty string '' that glues together all strings in the list and returns a new string.
  • The string on which you call the join method is used as a delimiter between the list elements.
  • If you don’t need a delimiter, just use the empty string ''.

Code: Let’s have a look at the code.

lst = ['learn ', 'python ', 'fast']
print(''.join(lst))

The output is:

learn python fast

However, what if you want to do something different. Rather than joining all strings in the list to a single string, you want to join the strings in the list in pairs.

Problem: Python Join List Pairs


Problem: Given a list of strings. Join the first with the second string, the second with the third, and so on.

Example: Let’s consider the following minimal example:

['x', 'y', 'v', 'w']

Is there any simple way to pair the first with the second and the third with the fourth string to obtain the following output?

['xy', 'vw']

Note that the length of the strings in the list is variable so the following would be a perfectly acceptable input:

['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff'] 

You can play with all three methods before diving into each of them:

Exercise: What’s the most Pythonic method?

Method 1: Zip() + List Comprehension


You can use the following smart one-liner solution

lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
out = [x + y for x,y in zip(lst[::2], lst[1::2])]
print(out)
# ['aaaab', 'ccdddd', 'eeefff']

The one-liner uses the following strategy:

  • Obtain two slices lst[::2] and lst[1::2] of the original list over every other element starting from the first and the second elements, respectively. If you need to refresh your slicing skills, check out my detailed blog article.
  • Zip the two slices to a sequence of tuples using the zip(...) function. This aligns the first with the second elements from the original list, the third with the forth, and so on. To refresh your zip() skills, check out my blog tutorial here.
  • Use list comprehension to iterate over each pair of values x,y and concatenate them using list concatenation x+y. For a refresher on list comprehension, check out this free tutorial—and for a refresher on list concatenation, check out this one.

Method 2: Iterator + List Comprehension


You can also use an iterator to accomplish this:

lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
it = iter(lst)
out = [x + next(it, '') for x in it] print(out)
# ['aaaab', 'ccdddd', 'eeefff']

Here’s the idea:

  • Create an iterator object it using the built-in function iter().
  • Use list comprehension to go over each element in the iterator.
  • Concatenate each element with the return value of calling the next() function on the iterator. This ensures that the iterator moves one position further iterating over the list. So, the next element x won’t be a duplicate.

Method 3: Use List Comprehension with Indexing


This method is the most straightforward one for Python beginners:

lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
out = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]
print(out)
# ['aaaab', 'ccdddd', 'eeefff']

The idea is simply to use the range function to iterate over every other index i=0, 2, 4, 5, ... to access the i-th and the i+1-th elements at the same time in the expression statement of list comprehension (to concatenate those with lst[i] + lst[i+1]).

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2020/06/...ist-pairs/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] List Comprehension in Python xSicKxBot 0 2,107 08-23-2023, 07:54 PM
Last Post: xSicKxBot
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 1,957 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,557 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,697 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 1,608 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python List of Tuples to DataFrame ? xSicKxBot 0 1,512 04-22-2023, 06:10 AM
Last Post: xSicKxBot
  [Tut] Python List of Dicts to Pandas DataFrame xSicKxBot 0 1,534 04-11-2023, 04:15 AM
Last Post: xSicKxBot
  [Tut] Python | Split String into List of Substrings xSicKxBot 0 1,442 12-11-2022, 12:17 PM
Last Post: xSicKxBot
  [Tut] Python Find in List [Ultimate Guide] xSicKxBot 0 1,430 12-09-2022, 11:35 PM
Last Post: xSicKxBot
  [Tut] Easiest Way to Convert List of Hex Strings to List of Integers xSicKxBot 0 1,460 11-25-2022, 11:54 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016