Fundamentals 6 min read

Python String and List Operations with Practical Code Examples

This article presents a collection of Python fundamentals covering string reversal, palindrome detection, unique element extraction, element equality checks, list flattening, element unpacking, finding top‑N values, memory size inspection, and various file I/O techniques, all illustrated with ready‑to‑run code snippets.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python String and List Operations with Practical Code Examples

The article introduces several useful Python techniques for handling strings and lists, starting with common string operations such as reversing a string, checking for palindromes, extracting unique characters, and comparing element composition.

String reversal examples:

# Method 1
s = 'hello  world'
print(s[::-1])

# Method 2
from functools import reduce
print(reduce(lambda x,y: y+x, s))

Palindrome check example (note the syntax error in the original source is corrected):

s1 = 'abccba'
s2 = 'abcde'

def func(s):
    if s == s[::-1]:
        print('回文')
    else:
        print('不回文')

func(s1)
func(s2)

Finding unique characters using a set and joining them back into a string, as well as deduplicating a list:

# String unique characters
s1 = 'wwweeerftttg'
print(''.join(set(s1)))  # e.g., 'ftgwer'

# List deduplication
l1 = [2, 4, 5, 6, 7, 1, 2]
print(list(set(l1)))  # [1, 2, 4, 5, 6, 7]

Checking whether two strings contain the same multiset of characters using collections.Counter :

from collections import Counter
s1, s2, s3 = 'asdf', 'fdsa', 'sfad'
c1, c2, c3 = Counter(s1), Counter(s2), Counter(s3)
if c1 == c2 and c2 == c3:
    print('符合')

The article then moves to list operations, showing how to flatten nested lists with iteration_utilities.deepflatten , unpack an iterable with the starred expression, and retrieve the largest or smallest N elements using heapq :

from iteration_utilities import deepflatten
l = [[12, 5, 3], [2.4, [5], [6, 9, 7]]]
print(list(deepflatten(l)))

first, *middle, last = grades  # *expression splits an iterable

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums))   # [42, 37, 23]
print(heapq.nsmallest(3, nums))  # [-4, 1, 2]

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])

Additional practical snippets demonstrate how to check an object's memory footprint with sys.getsizeof , use print with custom separators and end characters, and perform reading and writing of plain and compressed files (gzip, bz2):

import sys
s1 = 'a'
s2 = 'aaddf'
n1 = 32
print(sys.getsizeof(s1))  # 50
print(sys.getsizeof(s2))  # 54
print(sys.getsizeof(n1))  # 28

# Print to file
with open('somefile.txt', 'rt') as f:
    print('Hello World!', file=f)

# Custom separator and end
print('GKY', 1995, 5, 18, sep='-', end='!!\n')  # GKY-1995-5-18!!

# Read gzip file
import gzip
with open('somefile.gz', 'rt') as f:
    text = f.read()

# Write gzip file
with open('somefile.gz', 'wt') as f:
    f.write(text)

# Read bz2 file
import bz2
with open('somefile.bz2', 'rt') as f:
    text = f.read()

Overall, the collection serves as a quick‑reference guide for Python beginners and intermediate developers to perform everyday data manipulation and I/O tasks efficiently.

Pythoncode examplesFundamentalsstring-manipulationlist-manipulation
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login 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.