My Top 5 Python List Tricks

Zip, Map, Join, List Comprehensions and Set.

Jason Riedel
Nov 20, 2020

1) Turn a list into a string

It can be useful to swap in a delimiter other than space, like “,”.join(my_list)

In [1]: my_list = ['Follow', 'me', 'on', 'Twitter', 'and', 'LinkedIn']In [2]: my_string = " ".join(my_list)In [3]: print(my_string)
Follow me on Twitter and LinkedIn

2) Find the most frequent item in a list

In [1]: options = [‘Be Happy’, ‘Be Sad’, ‘Be Happy’, ‘Be Cool’, ‘Be Happy’]In [2]: most_frequent = max(set(options), key=options.count)In [3]: print(most_frequent)
Be Happy

3a) Changing every element in a list the long way

In [1]: my_kids = ['grayson', 'chase']In [2]: new_kids = []In [3]: for kid in my_kids:
...: new_kid = kid.capitalize()
...: new_kids.append(new_kid)
...:
In [4]: print(new_kids)
['Grayson', 'Chase']

3b) Alternatively, using a list comprehension

In [1]: my_kids = ['grayson', 'chase']In [2]: new_kids = [kid.capitalize() for kid in my_kids]In [3]: print(new_kids)
['Grayson', 'Chase']

3c) And Alternatively again using map

In [1]: my_kids = ['grayson', 'chase']In [2]: new_kids = map(str.capitalize,my_kids)In [3]: print(list(new_kids))
['Grayson', 'Chase']

4) Remove duplicates in a list by converting a list to a set then back to a list

In [1]: my_list = ['Follow me','Follow me','Follow me','Please']In [2]: my_list = list(set(my_list))In [3]: print(my_list)
['Follow me', 'Please']

5) Convert two lists into keys and values in a dictionary using zip

In [1]: my_kids = ['Grayson', 'Chase']In [2]: ages = [6, 5]In [3]: kids_ages = dict(zip(my_kids, ages))In [4]: print(kids_ages)
{'Grayson': 6, 'Chase': 5}

If you enjoy my content please follow me on LinkedIn and Twitter. Also check out my YouTube channel for video tutorials.

--

--

Jason Riedel
Jason Riedel

Written by Jason Riedel

Co-Founder and CTO at Aspireship, Tech Blog @ Tuxlabs, Former HipHop CEO, Former PayPal and Symantec Cloud Leadership

No responses yet