Home > Fun with Lists > Python

Fun with Lists

Python

Contents

1   Removing Elements

1.1   All values equal to x

x = 4

a = [1, 2, 3, 4, 4, 5, 6, 1, 4]
for i in range(a.count(x)):
    a.pop(a.index(x))
print(a)
[1, 2, 3, 5, 6, 1]
a = [1, 2, 3, 4, 4, 5, 6, 1, 4]
b = [v for v in a if v != x]
print(b)
[1, 2, 3, 5, 6, 1]
print(a)
[1, 2, 3, 4, 4, 5, 6, 1, 4]

1.2   Duplicates

Caution!

This approach will not preserve the order of the list items.

a = [1, 2, 3, 4, 3, 5, 1, 6]
b = list(set(a))
print(b)
[1, 2, 3, 4, 5, 6]

1.3   First element

a = [1, 2, 3, 4, 5, 6]
b = a.pop(0)
print(b)
1
print(a)
[2, 3, 4, 5, 6]
a = [1, 2, 3, 4, 5, 6]
del a[0]
print(a)
[2, 3, 4, 5, 6]
a = [1, 2, 3, 4, 5, 6]
d = a[1:]
print(d)
[2, 3, 4, 5, 6]
print(a)
[1, 2, 3, 4, 5, 6]

1.4   Last element

a = [1, 2, 3, 4, 5, 6]
b = a.pop()
print(b)
6
print(a)
[1, 2, 3, 4, 5]
a = [1, 2, 3, 4, 5, 6]
del a[-1]
print(a)
[1, 2, 3, 4, 5]
a = [1, 2, 3, 4, 5, 6]
c = a[:-1]
print(c)
[1, 2, 3, 4, 5]
print(a)
[1, 2, 3, 4, 5, 6]

1.5   nth element

n = 3

a = [1, 2, 3, 4, 5, 6]
b = a.pop(n - 1)
print(b)
3
print(a)
[1, 2, 4, 5, 6]
a = [1, 2, 3, 4, 5, 6]
del a[n - 1]
print(a)
[1, 2, 4, 5, 6]
a = [1, 2, 3, 4, 5, 6]
c = a[:n - 1] + a[n:]
print(c)
[1, 2, 4, 5, 6]
print(a)
[1, 2, 3, 4, 5, 6]
a = [1, 2, 3, 4, 5, 6]
c = [v for i, v in enumerate(a) if i != n - 1]
print(c)
[1, 2, 4, 5, 6]
print(a)
[1, 2, 3, 4, 5, 6]

2   Replacing Elements

2.1   All values equal to x

x = 4

a = [1, 2, 3, 4, 4, 5, 6, 1, 4]
for i in range(a.count(x)):
    a[a.index(x)] = 0
print(a)
[1, 2, 3, 0, 0, 5, 6, 1, 0]
a = [1, 2, 3, 4, 4, 5, 6, 1, 4]
b = [v if v != x else 0 for v in a ]
print(b)
[1, 2, 3, 0, 0, 5, 6, 1, 0]
print(a)
[1, 2, 3, 4, 4, 5, 6, 1, 4]

2.2   First element

a = [1, 2, 3, 4]
a[0] = 0
print(a)
[0, 2, 3, 4]
a = [1, 2, 3, 4]
b = [0] + a[1:]
print(b)
[0, 2, 3, 4]
print(a)
[1, 2, 3, 4]

2.3   Last element

a = [1, 2, 3, 4]
a[-1] = 0
print(a)
[1, 2, 3, 0]
a = [1, 2, 3, 4]
b = a[:-1] + [0]
print(b)
[1, 2, 3, 0]
print(a)
[1, 2, 3, 4]

2.4   nth element

n = 3

a = [1, 2, 3, 4]
a[n - 1] = 0
print(a)
[1, 2, 0, 4]
a = [1, 2, 3, 4]
b = [v if i != n -1 else 0 for i, v in enumerate(a)]
print(b)
[1, 2, 0, 4]
print(a)
[1, 2, 3, 4]

3   Sorting

3.1   Alphabetically (case-insensitive)

a = ['d', 'C', 'B', 'a']

b = sorted(a, key=lambda x: x.lower())
print(b)
['a', 'B', 'C', 'd']
print(a)
['d', 'C', 'B', 'a']
a.sort(key=lambda s: s.lower())
print(a)
['a', 'B', 'C', 'd']

3.2   Alphabetically (case-sensitive)

a = ['d', 'C', 'B', 'a']

b = sorted(a)
print(b)
['B', 'C', 'a', 'd']
print(a)
['d', 'C', 'B', 'a']
a.sort()
print(a)
['B', 'C', 'a', 'd']

3.3   Ascending order

a = ['a', 'c', 'd', 'b']

b = sorted(a, reverse=True)
print(b)
['d', 'c', 'b', 'a']
print(a)
['a', 'c', 'd', 'b']
a.sort(reverse=True)
print(a)
['d', 'c', 'b', 'a']

3.4   Strings by length

a = ['aaaa', 'B', 'CCC', 'dd']

b = sorted(a, key=lambda x: len(x))
print(b)
['B', 'dd', 'CCC', 'aaaa']
print(a)
['aaaa', 'B', 'CCC', 'dd']
a.sort(key=lambda x: len(x))
print(a)
['B', 'dd', 'CCC', 'aaaa']

4   Other

4.1   Add up all values in a list of numbers

a = [1, 2.5, 7, 13221, 4.6545]
b = sum(a)
print(b)
13236.1545

4.2   Append to a list

a = [1, 2, 3]
a.append(4)
print(a)
[1, 2, 3, 4]

4.3   Apply a function to every list element

def func(x):
    print(x)

def func_2(x):
    return 2*x

a = [1, 2, 3, 4]
map(func, a)
1
2
3
4
b = map(func_2, a)
print(b)
[2, 4, 6, 8]
c = [func_2(x) for x in a]
print(c)
[2, 4, 6, 8]

4.4   Cartesian product of 2 lists (vectors)

a = [1, 2, 3]
b = [4, 5, 6]

c = [(x, y) for x in a for y in b]
print(c)
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
import itertools
d = [p for p in itertools.product(a, b)]
print(d)
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

4.5   Cartesian product of n lists (vectors)

from pprint import pprint
import itertools

a = [[0, 1], [2, 3], [4, 5]]

b = [p for p in itertools.product(*a)]
pprint(b)
[(0, 2, 4),
 (0, 2, 5),
 (0, 3, 4),
 (0, 3, 5),
 (1, 2, 4),
 (1, 2, 5),
 (1, 3, 4),
 (1, 3, 5)]

4.6   Check if 2 lists have at least 1 common element

a = [1, 2, 0]
b = [3, 0, 4]

d = len((set(a) & set(b))) > 0
print(d)
True

4.7   Check if a list contains the value x

a = [1, 2.5, 7, 13221, 4.6545]
if 7 in a:
    print('yes')
else:
    print('no')
yes

4.8   Count the number of times x appears in a list

a = [1, 2.5, 7, 13221, 4.6545, 7]
b = a.count(7)
print(b)
2

4.9   Difference of 2 lists

a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

c = [x for x in a if not x in b]
print(c)
[1, 2]
d = list(set(a) - set(b))
print(d)
[1, 2]
e = list(set.difference(set(a), set(b)))
print(e)
[1, 2]

4.10   Difference of n lists

a = [1, 2, 3, 4]
b = [[3, 5, 6, 7], [1, 8, 9, 10]]

# a - b[0] - b[1]:

c = [x for x in a if not any([x in l for l in b])]
print(c)
[2, 4]
d = list(set(a).difference(*[set(l) for l in b]))
print(d)
[2, 4]

4.11   First n elements of a list

n = 2

a = [1, 2, 3, 4, 5, 6]
b = a[:2]
print(b)
[1, 2]

4.12   First n non-x elements of a list

n = 3
x = 2

a = [1, 2, 2, 3, 2, 2, 2, 4, 5, 6]

gen = (v for v in a if v != x)
b = [gen.next() for i in range(n)]
print(b)
[1, 3, 4]
c = []
for v in a:
    if v != x:
        c.append(v)
    if len(c) == n:
        break
print(c)
[1, 3, 4]

4.13   Flatten a list of lists

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = [i for s in a for i in s]
print(b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

4.14   Insert x after the first occurence of y

x = 4
y = 3
a = [1, 2, 3, 5, 3, 6, 2]

try:
    a.insert(a.index(y) + 1, x)
except ValueError:
    a.append(x)
print(a)
[1, 2, 3, 4, 5, 3, 6, 2]
a = [1, 2, 3, 5, 3, 6, 2]
try:
    i = a.index(y)
    b = a[:i + 1] + [x] + a[i + 1:]
except ValueError:
    b = a + [x]
print(b)
[1, 2, 3, 4, 5, 3, 6, 2]
print(a)
[1, 2, 3, 5, 3, 6, 2]

4.15   Insert x before the first occurence of y

x = 3
y = 4
a = [1, 2, 4, 5, 4, 6, 2]

try:
    a.insert(a.index(y), x)
except ValueError:
    a.append(x)
print(a)
[1, 2, 3, 4, 5, 4, 6, 2]
a = [1, 2, 4, 5, 4, 6, 2]
try:
    i = a.index(y)
    b = a[:i] + [x] + a[i:]
except ValueError:
    b = a + [x]
print(b)
[1, 2, 3, 4, 5, 4, 6, 2]
print(a)
[1, 2, 4, 5, 4, 6, 2]

4.16   Intersection of 2 lists

a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

c = [x for x in a if x in b]
print(c)
[3, 4]
d = list(set(a) & set(b))
print(d)
[3, 4]
e = list(set(a).intersection(b))
print(e)
[3, 4]

4.17   Intersection of n lists

a = [[1, 2, 3, 4], [3, 4, 5, 6], [1, 3, 7, 8]]

b = list(set.intersection(*[set(l) for l in a]))
print(b)
[3]
c = [x for x in a[0] if all([x in l for l in a[1:]])]
print(c)
[3]

4.18   Iterate over every other element of a list

a = [1, 2, 3, 4, 5, 6]
for x in a[::2]:
    print x
1
3
5

4.19   Iterate over index/value pairs of a list

a = [1, 2.5, 7, 13221, 4.6545]
for i, v in enumerate(a):
    print('%i: %i' % (i, v))
0: 1
1: 2
2: 7
3: 13221
4: 4

4.20   Iterate over the elements of a list

a = [1, 2, 3, 4]
for x in a:
    print x
1
2
3
4

4.21   Largest element from a list of numbers

a = [1, 2.5, 7, 13221, 4.6545]
b = max(a)
print(b)
13221

4.22   Last n elements of a list

n = 2

a = [1, 2, 3, 4, 5, 6]
b = a[-2:]
print(b)
[5, 6]

4.23   Length of a list

a = [1, 2, 3, 4]
l = len(a)
print(l)
4

4.24   Merge 2 lists

a = [1, 2, 3]
b = [4, 5, 6]

c = a + b
print(c)
[1, 2, 3, 4, 5, 6]
print(a)
[1, 2, 3]
print(b)
[4, 5, 6]
a.extend(b)
print(a)
[1, 2, 3, 4, 5, 6]
print(b)
[4, 5, 6]

4.25   Permutations of list elements

from pprint import pprint
from itertools import permutations as perm

a = ['a', 'b', 'c']

b = list(perm(a))
pprint(b)
[('a', 'b', 'c'),
 ('a', 'c', 'b'),
 ('b', 'a', 'c'),
 ('b', 'c', 'a'),
 ('c', 'a', 'b'),
 ('c', 'b', 'a')]
c = [''.join(p) for p in perm(a)]
print(c)
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
d = [''.join(p) for p in perm(a, 2)]
print(d)
['ab', 'ac', 'ba', 'bc', 'ca', 'cb']

4.26   Prepend an element to a list

a = [2, 3, 4]

a.insert(0, 1)
print(a)
[1, 2, 3, 4]
a = [2, 3, 4]
b = [1] + a
print(b)
[1, 2, 3, 4]
print(a)
[2, 3, 4]

4.27   Reverse the order of a list

a = [1, 2, 3, 4]
a.reverse()
print(a)
[4, 3, 2, 1]
a = [1, 2, 3, 4]
c = a[::-1]
print(c)
[4, 3, 2, 1]
print(a)
[1, 2, 3, 4]

4.28   Smallest element from a list of numbers

a = [1, 2.5, 7, 13221, 4.6545]
b = min(a)
print(b)
1

4.29   Symmetric difference of 2 lists

a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

c = [x for x in a if x not in b] + [x for x in b if x not in a]
print(c)
[1, 2, 5, 6]
d = list(set(a) ^ set(b))
print(d)
[1, 2, 5, 6]
e = list(set(a).symmetric_difference(b))
print(e)
[1, 2, 5, 6]

4.30   Symmetric difference of n lists

a = [[1, 2, 3, 4], [3, 4, 5, 6], [1, 5, 7, 8]]

b = a[0]
for i in range(len(a) - 1):
    b = list(set(b) ^ set(a[i + 1]))
print(b)
[2, 6, 7, 8]
tmp = {}
for v in [i for s in a for i in s]:
    tmp[v] = (v not in tmp)
c = [k for k, v in tmp.iteritems() if v]
print(c)
[2, 6, 7, 8]

4.31   Union of 2 lists

a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

c = [x for x in set(a + b)]
print(c)
[1, 2, 3, 4, 5, 6]
d = list(set(a) | set(b))
print(d)
[1, 2, 3, 4, 5, 6]
e = list(set(a).union(b))
print(e)
[1, 2, 3, 4, 5, 6]

4.32   Union of n lists

a = [[1, 2, 3, 4], [3, 4, 5, 6], [1, 6, 7, 8]]

b = list(set.union(*[set(l) for l in a]))
print(b)
[1, 2, 3, 4, 5, 6, 7, 8]
import itertools
c = [x for x in set(itertools.chain(*a))]
print(c)
[1, 2, 3, 4, 5, 6, 7, 8]

4.33   Zero-pad a list from the left

max_length = 10

a = [1, 2, 3, 4]

b = [0]*(max_length - len(a)) + a
print(b)
[0, 0, 0, 0, 0, 0, 1, 2, 3, 4]

4.34   Zero-pad a list from the right

max_length = 10

a = [1, 2, 3, 4]

b = a + [0]*(max_length - len(a))
print(b)
[1, 2, 3, 4, 0, 0, 0, 0, 0, 0]