{ "metadata": { "name": "", "signature": "sha256:794382d63f2196d47e8413154304f8cb041bbfa827396f24b4c8101e4e757cb6" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Flatten Lists Of Lists\n", "\n", "- **Author:** [Chris Albon](http://www.chrisalbon.com/), [@ChrisAlbon](https://twitter.com/chrisalbon)\n", "- **Date:** -\n", "- **Repo:** [Python 3 code snippets for data science](https://github.com/chrisalbon/code_py)\n", "- **Note:** Based on: http://howchoo.com/g/how-to-use-list-comprehension-in-python" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Create a list containing three lists of names\n", "list_of_lists = [['Amy','Betty','Cathryn','Dana'], \n", " ['Elizabeth','Fay','Gora'], \n", " ['Heidi','Jane','Kayley']]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "# For each element in list_of_lists, take each element in the list\n", "flattened_list = [i for row in list_of_lists for i in row]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "# View the flattened list\n", "flattened_list" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "['Amy',\n", " 'Betty',\n", " 'Cathryn',\n", " 'Dana',\n", " 'Elizabeth',\n", " 'Fay',\n", " 'Gora',\n", " 'Heidi',\n", " 'Jane',\n", " 'Kayley']" ] } ], "prompt_number": 9 } ], "metadata": {} } ] }