Efficiently concatenate two strings from tuples in a list?

2024/10/8 22:14:33

I want to concatenate the two string elements in a list of tuples

I have this:

mylist = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
myanswer = []for tup1 in mylist:myanswer.append(tup1[0] + tup[1])

It's working but is there any easy way to do this? My real list has around 1000 items and I don't think a for loop is the most efficient way.

Expected output:

myanswer = ["ab", "cd", "ef", "gh"]
Answer

Use a list comprehension, and for just two elements, I'd use tuple unpacking and concatenation:

myanswer = [s1 + s2 for s1, s2 in mylist]

Another option is to use a formatted string literal:

myanswer = [f"{s1}{s2}" for s1, s2 in mylist]

Both are reasonably fast:

>>> from random import choice
>>> from string import ascii_letters
>>> from timeit import Timer
>>> testdata = [(choice(ascii_letters), choice(ascii_letters)) for _ in range(10000)]
>>> count, total = Timer('[f"{s1}{s2}" for s1, s2 in mylist]', 'from __main__ import testdata as mylist').autorange()
>>> print(f"List comp with f-string, 10k elements: {total / count * 1000000:7.2f} microseconds")
List comp with f-string, 10k elements: 1249.37 microseconds
>>> count, total = Timer('[s1 + s2 for s1, s2 in mylist]', 'from __main__ import testdata as mylist').autorange()
>>> print(f"List comp with concatenation, 10k elements: {total / count * 1000000:6.2f} microseconds")
List comp with concatenation, 10k elements: 1061.89 microseconds

Concatenation wins out here.

A list comprehension removes the need to look up the list object and its .append() method each time in a loop, see What is the advantage of a list comprehension over a for loop?

Formatted string literals where introduced in Python 3.6, and are easily the fastest way of composing strings with interpolated elements (even though they didn't start out that way).

I also tried out [itertools.starmap()] with [operator.add()] and [str.join()], but this doesn't appear to be competitive:

>>> count, total = Timer('list(starmap(add, mylist))', 'from __main__ import testdata as mylist; from itertools import starmap; from operator import add').autorange()
>>> print(f"itertools.starmap and operator.add, 10k elements: {total / count * 1000000:6.2f} microseconds")
itertools.starmap and operator.add, 10k elements: 1275.02 microseconds
>>> count, total = Timer('list(starmap(str.join, mylist))', 'from __main__ import testdata as mylist; from itertools import starmap').autorange()
>>> print(f"itertools.starmap and str.join, 10k elements: {total / count * 1000000:6.2f} microseconds")
itertools.starmap and str.join, 10k elements: 1564.79 microseconds

It does improve with more elements; by 1 million elements, map(starmap(add, largelist)) is winning by a small margin (133ms vs 140ms for a list comprehension with concatenation).

https://en.xdnf.cn/q/118668.html

Related Q&A

How to assert that a function call does not return an error with unittest?

Is there anyway with unittest to just assert that a function call does not result in an error, whether it is a TypeError, IOError, etc.example:assert function(a,b) is not errororif not assertRaises fun…

How to calculate Python float-number-th root of float number

I found the following answer here on Stackoverflow:https://stackoverflow.com/a/356187/1829329But it only works for integers as n in nth root:import gmpy2 as gmpyresult = gmpy.root((1/0.213), 31.5).real…

Need help making a Hilbert Curve using numbers in Python

I want to make a function that will create a Hilbert Curve in python using numbers. The parameters for the function would be a number and that will tell the function how many times it should repeat. To…

How do I separate each list [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Why python doesnt see the members of quantumCircuit class qiskit

I`m trying to learn the programming on quantum computers. I have installed qiskit in VS Code (all qiskit extentions available in VS Code market) , python compilator (from Vs Code market "Python&qu…

Compare multiple lines in a text file using python

Im writing a program that is time tracking report that reports the time that was spent in each virtual machine, I`m having a problem comparing the txt file cause the only thing that changes are the num…

Error installing eomaps through conda and pip

I am getting the following error output when trying to install eomaps using Conda. I dont know how to solve this. I have also tried the same using pip but it didnt seem to solve the problem. Here is th…

DFS on a graph using a python generator

I am using a generator to do a full search on a graph, the real data set is fairly large, here is a portion of the code i wrote on a small data set:class dfs:def __init__(self):self.start_nodes = [1,2]…

Importing test libraries failed. No module named a

I have a folder /example which contains /Libs which further contains different folders /a, /b each containing python libraries. I am trying to run a robot framework code from /example.The error it show…

Sorting characters by count using PHP or Python

I have a string of charactersabcdefghijklmnopqrstuvwxyz_ I want to take this string of characters and sort them by the number of times they appear in a large block of characters. For example: cwrxwzb…