Four copies of the last two characters

Four copies of the last two characters

EasyString Programs · 3 of 106

Write a Python program to make a string of 4 copies of the last two characters of a string (length must be at least 2).

Input
"Python"
Output
onononon

Approach

  1. Slice the last two characters and repeat them with * 4.

Solution

Python
text = "Python"if len(text) >= 2:    print(text[-2:] * 4)else:    print("String must have at least 2 characters")
Output
onononon

Line by line

Line 3

text[-2:] is “on”; multiplying a string repeats it.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Length of the longest string in a list

Length of the longest string in a list

EasyString Programs · 2 of 106

Write a Python program that returns the length of the longest string in a list.

Input
["python", "is", "readable", "fun"]
Output
8 | 8 | readable

Approach

  1. Compare lengths in a loop, or use max() with len.

Solution

Python
words = ["python", "is", "readable", "fun"]longest = 0for w in words:    if len(w) > longest:        longest = len(w)print(longest, "|", max(len(w) for w in words), "|", max(words, key=len))
Output
8 | 8 | readable

Line by line

Lines 3-5

Keep the biggest length seen so far.

Line 6

max(len(w) for w in words) does the same in one line; max(words, key=len) returns the word itself.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

First and last 2 characters

First and last 2 characters

EasyString Programs · 1 of 106

Write a Python program to build a string from the first 2 and the last 2 characters of a string. If the string is shorter than 2 characters, return an empty string.

Input
"Sqatools", "Py", "S"
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Approach

  1. Check the length first; then join two slices.

Solution

Python
def ends(text):    if len(text) < 2:        return ""    return text[:2] + text[-2:] for t in ["Sqatools", "Py", "S"]:    print(repr(t), "->", repr(ends(t)))
Output
'Sqatools' -> 'Sqls'
'Py' -> 'PyPy'
'S' -> ''

Line by line

Lines 2-3

Strings shorter than 2 characters return an empty string, as the task asks.

Line 4

text[:2] is the first two characters and text[-2:] the last two.

Note

For “Py” the two slices overlap, so the result is “PyPy”.

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs

Round every number and sum

Python Practice › List Programs › Program 99

Round every number and sum

EasyList Programs · 99 of 100

Write a Python program to round every number in a list and print the sum of the rounded numbers multiplied by the list length.

Input
[22.4, 4.0, -16.22, -9.1, 11.0, -12.22, 14.2, -5.2, 17.5]
Output
[22, 4, -16, -9, 11, -12, 14, -5, 18]
243

Approach

  1. Round each value with round(), add them, multiply by the length.

Solution

Python
numbers = [22.4, 4.0, -16.22, -9.1, 11.0, -12.22, 14.2, -5.2, 17.5]rounded = [round(n) for n in numbers]print(rounded)print(sum(rounded) * len(numbers))
Output
[22, 4, -16, -9, 11, -12, 14, -5, 18]
243

Line by line

Line 2

round(17.5) is 18 and round(-12.22) is -12; ties go to the even number.

Note

The sum of the rounded numbers is 27; multiplied by the 9 items it is 243.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Decode a run-length encoded list

Python Practice › List Programs › Program 98

Decode a run-length encoded list

MediumList Programs · 98 of 100

Write a Python program to decode a run-length encoded list, where [n, x] means x repeated n times.

Input
[[2, 1], 2, 3, [2, 4], 5, 1]
Output
[1, 1, 2, 3, 4, 4, 5, 1]

Approach

  1. Expand [n, x] pairs; copy plain items.

Solution

Python
encoded = [[2, 1], 2, 3, [2, 4], 5, 1]decoded = []for item in encoded:    if isinstance(item, list):        count, value = item        decoded.extend([value] * count)    else:        decoded.append(item)print(decoded)
Output
[1, 1, 2, 3, 4, 4, 5, 1]

Line by line

Lines 5-6

[value] * count repeats the value.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Remove repeated dictionaries

Python Practice › List Programs › Program 97

Remove repeated dictionaries

EasyList Programs · 97 of 100

Write a Python program to remove repeated dictionaries from a list.

Input
[{"Hello": 5}, {"student": 7}, {"are": 3}, {"learning": 8}, {"Hello": 5}, {"Language": 8}, {"are": 3}]
Output
[{'Hello': 5}, {'student': 7}, {'are': 3}, {'learning': 8}, {'Language': 8}]

Approach

  1. Use a set of each dict’s items (as a frozenset) to remember what was seen.

Solution

Python
data = [{"Hello": 5}, {"student": 7}, {"are": 3}, {"learning": 8}, {"Hello": 5}, {"Language": 8}, {"are": 3}]seen = set()result = []for d in data:    key = frozenset(d.items())    if key not in seen:        seen.add(key)        result.append(d)print(result)
Output
[{'Hello': 5}, {'student': 7}, {'are': 3}, {'learning': 8}, {'Language': 8}]

Line by line

Line 4

frozenset(d.items()) is a hashable fingerprint of the dict, so the check is fast even for long lists.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Word lengths as a dictionary

Python Practice › List Programs › Program 96

Word lengths as a dictionary

EasyList Programs · 96 of 100

Write a Python program to build a dictionary of each word and its length.

Input
["Hello", "student", "are", "learning", "Python", "Its", "Language"]
Output
{'Hello': 5, 'student': 7, 'are': 3, 'learning': 8, 'Python': 6, 'Its': 3, 'Language': 8}

Approach

  1. A dict comprehension.

Solution

Python
words = ["Hello", "student", "are", "learning", "Python", "Its", "Language"]print({w: len(w) for w in words})
Output
{'Hello': 5, 'student': 7, 'are': 3, 'learning': 8, 'Python': 6, 'Its': 3, 'Language': 8}

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Remove the 2nd character of each word

Python Practice › List Programs › Program 95

Remove the 2nd character of each word

EasyList Programs · 95 of 100

Write a Python program to remove the 2nd character of each word.

Input
["Hello", "student", "are", "learning", "Python", "Its", "Python", "Language"]
Output
['Hllo', 'sudent', 'ae', 'larning', 'Pthon', 'Is', 'Pthon', 'Lnguage']

Approach

  1. Join the slices before and after index 1.

Solution

Python
words = ["Hello", "student", "are", "learning", "Python", "Its", "Python", "Language"]print([w[0] + w[2:] for w in words])
Output
['Hllo', 'sudent', 'ae', 'larning', 'Pthon', 'Is', 'Pthon', 'Lnguage']

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Capitalise the 3rd character of each word

Python Practice › List Programs › Program 94

Capitalise the 3rd character of each word

EasyList Programs · 94 of 100

Write a Python program to make the 3rd character of each word uppercase.

Input
["Hello", "student", "are", "learning", "Python", "Its", "Python", "Language"]
Output
['HeLlo', 'stUdent', 'arE', 'leArning', 'PyThon', 'ItS', 'PyThon', 'LaNguage']

Approach

  1. Index 2 is the 3rd character; rebuild the word around it.

Solution

Python
words = ["Hello", "student", "are", "learning", "Python", "Its", "Python", "Language"]print([w[:2] + w[2].upper() + w[3:] if len(w) > 2 else w for w in words])
Output
['HeLlo', 'stUdent', 'arE', 'leArning', 'PyThon', 'ItS', 'PyThon', 'LaNguage']
Note

The original sample changed the 4th character (“HelLo”). The 3rd character is index 2, which gives “HeLlo”.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Replace a word in a list

Python Practice › List Programs › Program 93

Replace a word in a list

EasyList Programs · 93 of 100

Write a Python program to replace “Java” with “Python” in a list of words.

Input
["Hello", "student", "are", "learning", "Java", "Its", "Java", "Language"]
Output
['Hello', 'student', 'are', 'learning', 'Python', 'Its', 'Python', 'Language']

Approach

  1. Map each word, replacing the match.

Solution

Python
words = ["Hello", "student", "are", "learning", "Java", "Its", "Java", "Language"]print(["Python" if w == "Java" else w for w in words])
Output
['Hello', 'student', 'are', 'learning', 'Python', 'Its', 'Python', 'Language']

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs