Fundamentals 5 min read

How to Concatenate Nested Python Lists into a Formatted String

This article explains how to transform a nested Python list of label‑value pairs into a single formatted string using simple loops and list comprehensions, providing clear code examples and step‑by‑step explanations for beginners.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Concatenate Nested Python Lists into a Formatted String

Problem Overview

A user asked how to convert a nested list like [["TDD", "(38套)"], ["2TR", "(23套)"], ["FDD", "(18套)"]] into a single string where each pair is concatenated and separated by line breaks, e.g. "TDD(38套)\n2TR(23套)\nFDD(18套)".

Solution 1 – Simple Loop

list1 = [["TDD", "(38套)"], ["2TR", "(23套)"], ["FDD", "(18套)"]]
string1 = ""
for item in list1:
    string1 += item[0] + item[1] + "
"
print(string1)

This loop iterates over each sub‑list, concatenates the two elements, appends a newline, and prints the result.

Solution 2 – Using a List and join

list1 = [["TDD", "(38套)"], ["2TR", "(23套)"], ["FDD", "(18套)"]]
text = []
for data in list1:
    data1 = data[0] + data[1]
    text.append(data1)
final_text = "
".join(str(i) for i in text)
print(final_text)

This approach builds a temporary list of the concatenated pairs and then joins them with newline characters, achieving the same output.

Solution 3 – One‑Liner with List Comprehension

list1 = [["TDD", "(38套)"], ["2TR", "(23套)"], ["FDD", "(18套)"]]
result = "
".join([a + b for a, b in list1])
print(result)

The list comprehension directly creates the formatted strings, and join combines them.

All three methods produce the expected formatted string and can be chosen based on readability preferences.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Code TutorialString concatenationlist manipulation
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.