{"id":117255,"date":"2020-08-28T08:57:22","date_gmt":"2020-08-28T08:57:22","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=12353"},"modified":"2020-08-28T08:57:22","modified_gmt":"2020-08-28T08:57:22","slug":"python-one-line-array","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/08\/28\/python-one-line-array\/","title":{"rendered":"Python One Line Array"},"content":{"rendered":"<p>This article answers a number of questions how to accomplish different things with a Python array in one line. By studying these questions, you&#8217;ll become a better coder. So, let&#8217;s roll up your sleeves and get started! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2>Python One Line Print Array<\/h2>\n<p>If you just want to know the best way to print an array (list) in Python, here&#8217;s the short answer:<\/p>\n<ul>\n<li>Pass a list as an input to the <code><a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\">print()<\/a><\/code> function in Python. <\/li>\n<li>Use the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/what-is-asterisk-in-python\/\" target=\"_blank\">asterisk operator <\/a><code>*<\/code> in front of the list to &#8220;unpack&#8221; the list into the print function. <\/li>\n<li>Use the <code>sep<\/code> argument to define how to separate two list elements visually. <\/li>\n<\/ul>\n<p>Here&#8217;s the code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Create the Python List\nlst = [1, 2, 3, 4, 5] # Use three underscores as separator\nprint(*lst, sep='___')\n# 1___2___3___4___5 # Use an arrow as separator\nprint(*lst, sep='-->')\n# 1-->2-->3-->4-->5<\/pre>\n<p>Try It Yourself in Our Interactive Code Shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/pythonlistprint3?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"700px\" frameborder=\"no\"><\/iframe> <\/p>\n<p>This is the best and most Pythonic way to print a Python array list. If you still want to learn about alternatives&#8212;and improve your Python skills in the process of doing so&#8212;read the following tutorial!<\/p>\n<p><strong>Related Article<\/strong>:<a href=\"https:\/\/blog.finxter.com\/print-python-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Print a Python List Beautifully [Click &amp; Run Code]\"> Print a Python List Beautifully [Click &amp; Run Code]<\/a><\/p>\n<h2>Python If Else One Line Array<\/h2>\n<p>The most basic <a href=\"https:\/\/blog.finxter.com\/python-one-line-ternary\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line Ternary\">ternary operator<\/a> <code>x if c else y<\/code> returns expression <code>x<\/code> if the Boolean expression <code>c<\/code> evaluates to <code>True<\/code>. Otherwise, if the expression <code>c<\/code> evaluates to <code>False<\/code>, the ternary operator returns the alternative expression <code>y<\/code>.<\/p>\n<p>Here&#8217;s a minimal example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var = 21 if 3&lt;2 else 42\n# var == 42<\/pre>\n<p>While you read through the article to boost your one-liner power, you can listen to my detailed video explanation:<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-rich is-provider-embed-handler wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"If-Then-Else in One Line Python\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/ZGUAaQiO06Y?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/p><\/div>\n<\/figure>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/if-then-else-in-one-line-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"If-Then-Else in One Line Python [Video + Interactive Code Shell]\">If-Then-Else in One Line Python [Video + Interactive Code Shell]<\/a><\/p>\n<h2>Python One Line For Loop Array<\/h2>\n<p><strong>How to Write a For Loop in a Single Line of Python Code?<\/strong><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python One Line For Loop [A Simple Tutorial]\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/M6XNZ40lRFQ?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>There are two ways of writing a <a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-with-if\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line For Loop With If\">one-liner for loop<\/a>:<\/p>\n<ul>\n<li><strong>Method 1<\/strong>: If the <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Loops\">loop <\/a>body consists of one statement, simply write this statement into the same line: <code>for i in range(10): print(i)<\/code>. This prints the first 10 numbers to the shell (from 0 to 9). <\/li>\n<li><strong>Method 2: <\/strong>If the purpose of the loop is to create a list, use <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">list comprehension<\/a> instead: <code>squares = [i**2 for i in range(10)]<\/code>. The code squares the first ten numbers and stores them in the array list <code>squares<\/code>. <\/li>\n<\/ul>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/27248749cf\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p>Let&#8217;s have a look at both variants in more detail in the following article:<\/p>\n<p><strong>Related article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-one-line-for-loop-a-simple-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python One Line For Loop [A Simple Tutorial]\">Python One Line For Loop [A Simple Tutorial]<\/a><\/p>\n<h2>Python Iterate Array One Line<\/h2>\n<p><strong><em>How to iterate over an array in a single line of code? <\/em><\/strong><\/p>\n<p>Say, you&#8217;ve given an array (list) <code>lst<\/code> and you want to iterate over all values and do something with them. You can accomplish this using <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">list comprehension<\/a>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = [1, 2, 3]\nsquares = [i**2 for i in lst]\nprint(squares)\n# [1, 4, 9]<\/pre>\n<p>You iterate over all values in the array <code>lst<\/code> and calculate their square numbers. The result is stored in a new array list <code>squares<\/code>. <\/p>\n<p>You can even print all the squared array values in a single line by creating a dummy array of None values using the print() function in the expression part of the list comprehension statement:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[print(i**2) for i in lst] '''\n1\n4\n9 '''<\/pre>\n<p><strong>Related article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">List Comprehension Full Introduction<\/a><\/p>\n<h2>Python Fill Array One Line<\/h2>\n<p><strong><em>Do you want to fill or initialize an array with n values using only a single line of Python code?<\/em><\/strong> <\/p>\n<p>To fill an array with an integer value, use the list multiplication feature:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">array = [0] * 10\nprint(array)\n# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]<\/pre>\n<p>This creates an array of ten elements filled with the value 0. You can also fill the array with other elements by replacing the 0 with the desired element&#8212;for example, <code>[None] * 10<\/code> creates a list of ten <code>None<\/code> elements. <\/p>\n<h2>Python Initialize Array One Line<\/h2>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"How to Create a Python List?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/qXOFngx0bQU?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>There are many ways of creating an array (list) in Python. Let&#8217;s get a quick overview in the following table:<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Code<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>[]<\/code><\/td>\n<td><strong>Square bracket<\/strong>: Initializes an empty list with zero elements. You can add elements later.<\/td>\n<\/tr>\n<tr>\n<td><code>[x1, x2, x3, \u2026 ]<\/code><\/td>\n<td><strong>List display:<\/strong> Initializes an empty list with elements <code>x1<\/code>, <code>x2<\/code>, <code>x3<\/code>, &#8230; For example, <code>[1, 2, 3]<\/code> creates a list with three integers 1, 2, and 3.<\/td>\n<\/tr>\n<tr>\n<td><code>[expr1, expr2, ... ]<\/code><\/td>\n<td><strong>List display with expressions<\/strong>: Initializes a list with the result of the expressions <code>expr1<\/code>, <code>expr2<\/code>, &#8230; For example, <code>[1+1, 2-1]<\/code> creates the list <code>[2, 1]<\/code>. <\/td>\n<\/tr>\n<tr>\n<td><code>[expr for var in iter]<\/code><\/td>\n<td><strong>List comprehension<\/strong>: applies the expression <code>expr<\/code> to each element in an iterable.<\/td>\n<\/tr>\n<tr>\n<td><code>list(iterable)<\/code><\/td>\n<td><strong>List constructor<\/strong> that takes an iterable as input and returns a new list.<\/td>\n<\/tr>\n<tr>\n<td><code>[x1, x2, ...] * n<\/code><\/td>\n<td><strong>List multiplication<\/strong> creates a list of n concatenations of the list object. For example <code>[1, 2] * 2 == [1, 2, 1, 2]<\/code>.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>You can play with some examples in our interactive Python shell:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/c1e9402361\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"500\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Use <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">list comprehension<\/a> to create a list of square numbers.<\/em><\/p>\n<p>Let&#8217;s dive into some more specific ways to create various forms of lists in <a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\" title=\"Python Programming Tutorial [+Cheat Sheets]\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a>. <\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-create-a-python-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Create a Python List?\">How to Create a Python List?<\/a><\/p>\n<h2>Python Filter Array One Line<\/h2>\n<p><strong><em>How can you filter an array in Python using an arbitrary condition?<\/em><\/strong><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"How to Filter a List in Python?\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/3nG4TLkqzf8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/repl.it\/@finxter\/filterlistpython?lite=true\" scrolling=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\" width=\"100%\" height=\"400px\" frameborder=\"no\"><\/iframe> <\/p>\n<p>The most Pythonic way of filtering an array is the list comprehension statement <code>[x for x in list if condition]<\/code>. You can replace <code>condition<\/code> with any function of <code>x<\/code> you would like to use as a filtering criterion. <\/p>\n<p>For example, if you want to filter all elements that are smaller than, say, 10, you&#8217;d use the list comprehension statement <code>[x for x in list if x&lt;10]<\/code> to <a href=\"https:\/\/blog.finxter.com\/how-to-create-a-python-list\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Create a Python List?\">create a new list<\/a> with all list elements that are smaller than 10. <\/p>\n<p>Here are three examples of filtering a list:<\/p>\n<ul>\n<li>Get elements smaller than eight: <code>[x for x in lst if x&lt;8]<\/code>.<\/li>\n<li>Get even elements: <code>[x for x in lst if x%2==0]<\/code>.<\/li>\n<li>Get odd elements: <code>[x for x in lst if x%2]<\/code>.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = [8, 2, 6, 4, 3, 1] # Filter all elements &lt;8\nsmall = [x for x in lst if x&lt;8]\nprint(small) # Filter all even elements\neven = [x for x in lst if x%2==0]\nprint(even) # Filter all odd elements\nodd = [x for x in lst if x%2]\nprint(odd)<\/pre>\n<p>The output is:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Elements &lt;8\n[2, 6, 4, 3, 1] # Even Elements\n[8, 2, 6, 4] # Odd Elements\n[3, 1]<\/pre>\n<p>This is the most efficient way of filtering an array and it&#8217;s also the most Pythonic one.<\/p>\n<p><strong>Related Article<\/strong>: <a href=\"https:\/\/blog.finxter.com\/how-to-filter-a-list-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"How to Filter a List in Python?\">How to Filter a List in Python?<\/a><\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy\/nongreedy operators<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting<\/p>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners Now!!<\/em><\/a><\/strong><\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article answers a number of questions how to accomplish different things with a Python array in one line. By studying these questions, you&#8217;ll become a better coder. So, let&#8217;s roll up your sleeves and get started! Python One Line Print Array If you just want to know the best way to print an array [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-117255","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117255","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=117255"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117255\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=117255"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=117255"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=117255"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}