Fundamentals 5 min read

Master Python String & List Tricks: Reverse, Palindromes, Unique Elements & More

This guide demonstrates essential Python techniques for manipulating strings and lists, covering reversal, palindrome detection, extracting unique characters, element comparison, list flattening, iterable decomposition, retrieving top N items, memory inspection, custom printing, and handling compressed files.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python String & List Tricks: Reverse, Palindromes, Unique Elements & More

String Operations

1. Reverse a string

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

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

2. Check if a string is a palindrome

Use string reversal to determine palindrome status.

s1 = 'abccba'
s2 = 'abcde'

def func(s):
    if s == s[::-1]:
        print('Palindrome')
    else:
        print('Not palindrome')

func(s1)
func(s2)

3. Find unique characters in a string

Use set to deduplicate.

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

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

4. Compare if strings contain the same elements

Elements are considered the same if they have identical counts regardless of order.

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('Match')

List Operations

1. Flatten a nested list

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

2. Decompose an iterable of arbitrary length

first, *middle, last = grades  # * unpacks the middle part

3. Get the N largest or smallest elements

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'])

Other Utilities

1. Check object memory usage

import sys

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

2. Print variations

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

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

3. Read and write compressed files

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

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

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

with open('somefile.bz', 'wt') as f:
    f.write(text)
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.

fundamentalsCoding Tipsdata-structuresString Manipulationlist manipulation
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.