Flatten a nested list

Python Practice › List Programs › Program 90

Flatten a nested list

MediumList Programs · 90 of 100

Write a Python program to flatten a nested list.

Input
[0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
Output
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]

Approach

  1. Add plain items directly and the contents of sub-lists one by one (recursively for deeper nesting).

Solution

Python
def flatten(items):    flat = []    for item in items:        if isinstance(item, list):            flat.extend(flatten(item))        else:            flat.append(item)    return flat print(flatten([0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]))
Output
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]

Line by line

Lines 4-5

A sub-list is flattened by calling the same function on it, so any depth works.

Learn the concept

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

More list programs

← All 100 List Programs

Palindrome strings in a list

Python Practice › List Programs › Program 89

Palindrome strings in a list

EasyList Programs · 89 of 100

Write a Python program to get the palindrome strings from a list.

Input
["data", "python", "oko", "test", "ete"]
Output
['oko', 'ete']

Approach

  1. Keep words equal to their reverse.

Solution

Python
words = ["data", "python", "oko", "test", "ete"]print([w for w in words if w == w[::-1]])
Output
['oko', 'ete']

Learn the concept

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

More list programs

← All 100 List Programs

Percentage from marks

Python Practice › List Programs › Program 88

Percentage from marks

EasyList Programs · 88 of 100

Write a Python program to calculate the percentage from a list of marks out of 100 each.

Input
[80, 50, 70, 90, 95]
Output
77%

Approach

  1. Total obtained divided by total possible, times 100.

Solution

Python
marks = [80, 50, 70, 90, 95]percent = sum(marks) / (len(marks) * 100) * 100print(f"{percent:.0f}%")
Output
77%

Learn the concept

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

More list programs

← All 100 List Programs

Bill per fruit purchased

Python Practice › List Programs › Program 87

Bill per fruit purchased

MediumList Programs · 87 of 100

Write a Python program to calculate the bill for each fruit purchased, from a price list and a quantity list.

Input
prices [["apple", 30], ["mango", 50], ["banana", 20], ["lichi", 50]]; bought [["apple", 2], ["mango", 10]]
Output
Fruit: Apple    Bill: 60
Fruit: Mango    Bill: 500
Total: 560

Approach

  1. Turn the price list into a dict for lookup, then multiply price by quantity.

Solution

Python
prices = dict([["apple", 30], ["mango", 50], ["banana", 20], ["lichi", 50]])bought = [["apple", 2], ["mango", 10]]total = 0for fruit, qty in bought:    bill = prices[fruit] * qty    total += bill    print(f"Fruit: {fruit.capitalize():8} Bill: {bill}")print("Total:", total)
Output
Fruit: Apple    Bill: 60
Fruit: Mango    Bill: 500
Total: 560

Line by line

Line 1

dict() accepts a list of [key, value] pairs.

Learn the concept

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

More list programs

← All 100 List Programs

Insert a sublist at an index

Python Practice › List Programs › Program 86

Insert a sublist at an index

EasyList Programs · 86 of 100

Write a Python program to insert a sublist into a list at a given index.

Input
[4, 6, 8, 2, 3, 5], sublist [5, 2, 6], index 3
Output
[4, 6, 8, [5, 2, 6], 2, 3, 5]
[4, 6, 8, 5, 2, 6, 2, 3, 5]

Approach

  1. insert adds the sublist as one item; slice assignment adds its items.

Solution

Python
items = [4, 6, 8, 2, 3, 5]nested = items.copy()nested.insert(3, [5, 2, 6])print(nested) flat = items.copy()flat[3:3] = [5, 2, 6]print(flat)
Output
[4, 6, 8, [5, 2, 6], 2, 3, 5]
[4, 6, 8, 5, 2, 6, 2, 3, 5]

Line by line

Line 3

The sublist becomes one element.

Line 7

Assigning to the empty slice [3:3] splices the items in.

Learn the concept

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

More list programs

← All 100 List Programs

Remove duplicates with a set

Python Practice › List Programs › Program 85

Remove duplicates with a set

EasyList Programs · 85 of 100

Write a Python program to remove duplicates from a list using a set.

Input
[2, 5, 7, 8, 2, 3, 4, 12, 5, 6]
Output
[2, 3, 4, 5, 6, 7, 8, 12]
[2, 5, 7, 8, 3, 4, 12, 6]

Approach

  1. set() removes duplicates; use sorted(..., key=items.index) to restore the original order.

Solution

Python
items = [2, 5, 7, 8, 2, 3, 4, 12, 5, 6]unique = set(items)print(sorted(unique))print(sorted(unique, key=items.index))
Output
[2, 3, 4, 5, 6, 7, 8, 12]
[2, 5, 7, 8, 3, 4, 12, 6]

Line by line

Line 4

Sorting by each value’s first index restores the original order.

Learn the concept

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

More list programs

← All 100 List Programs

Dictionary from two lists

Python Practice › List Programs › Program 84

Dictionary from two lists

EasyList Programs · 84 of 100

Write a Python program to create a dictionary from a list of keys and a list of values.

Input
["a", "b", "c", "d", "e"], [234, 123, 456, 343, 223]
Output
{'a': 234, 'b': 123, 'c': 456, 'd': 343, 'e': 223}

Approach

  1. dict(zip(keys, values)).

Solution

Python
keys = ["a", "b", "c", "d", "e"]values = [234, 123, 456, 343, 223]print(dict(zip(keys, values)))
Output
{'a': 234, 'b': 123, 'c': 456, 'd': 343, 'e': 223}

Learn the concept

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

More list programs

← All 100 List Programs

Remove n elements from the left or right

Python Practice › List Programs › Program 83

Remove n elements from the left or right

EasyList Programs · 83 of 100

Write a Python program to remove n elements from the left and from the right of a list.

Input
[2, 5, 7, 9, 3, 4], n = 1 and 2
Output
remove 1 from left: [5, 7, 9, 3, 4] | from right: [2, 5, 7, 9, 3]
remove 2 from left: [7, 9, 3, 4] | from right: [2, 5, 7, 9]

Approach

  1. items[n:] drops from the left, items[:-n] from the right.

Solution

Python
items = [2, 5, 7, 9, 3, 4]for n in [1, 2]:    print(f"remove {n} from left:", items[n:], f"| from right:", items[:-n])
Output
remove 1 from left: [5, 7, 9, 3, 4] | from right: [2, 5, 7, 9, 3]
remove 2 from left: [7, 9, 3, 4] | from right: [2, 5, 7, 9]

Learn the concept

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

More list programs

← All 100 List Programs

Prime numbers in a list

Python Practice › List Programs › Program 82

Prime numbers in a list

EasyList Programs · 82 of 100

Write a Python program to get the prime numbers from a list.

Input
[11, 8, 7, 19, 6, 29]
Output
[11, 7, 19, 29]

Approach

  1. Keep numbers with no divisor from 2 to √n.

Solution

Python
def is_prime(n):    return n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1)) print([n for n in [11, 8, 7, 19, 6, 29] if is_prime(n)])
Output
[11, 7, 19, 29]

Learn the concept

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

More list programs

← All 100 List Programs

Count vowels in a list of words

Python Practice › List Programs › Program 81

Count vowels in a list of words

EasyList Programs · 81 of 100

Write a Python program to count the vowels in a list of words.

Input
["Learning", "Python", "From", "SqaTool"]
Output
8

Approach

  1. Join and count characters in “aeiou”.

Solution

Python
words = ["Learning", "Python", "From", "SqaTool"]print(sum(ch in "aeiouAEIOU" for w in words for ch in w))
Output
8
Note

The words contain 3 + 1 + 1 + 3 = 8 vowels.

Learn the concept

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

More list programs

← All 100 List Programs