Python One Line Array

5/5 - (1 vote)

This article answers a number of questions how to accomplish different things with a Python array in one line. By studying these questions, you’ll become a better coder. So, let’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 (list) in Python, here’s the short answer:

  • Pass a list as an input to the print() function in Python.
  • Use the asterisk operator * in front of the list to “unpack” the list into the print function.
  • Use the sep argument to define how to separate two list elements visually.

Here’s the code:

# Create the Python List
lst = [1, 2, 3, 4, 5]

# Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5

# Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5

Try It Yourself in Our Interactive Code Shell:

This is the best and most Pythonic way to print a Python array list. If you still want to learn about alternatives—and improve your Python skills in the process of doing so—read the following tutorial!

Related Article: Print a Python List Beautifully [Click & Run Code]

Python If Else One Line Array

The most basic ternary operator x if c else y returns expression x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative expression y.

Here’s a minimal example:

var = 21 if 3<2 else 42
# var == 42

While you read through the article to boost your one-liner power, you can listen to my detailed video explanation:

If-Then-Else in One Line Python

Related Article: If-Then-Else in One Line Python [Video + Interactive Code Shell]

Python One Line For Loop Array

How to Write a For Loop in a Single Line of Python Code?

Python One Line For Loop [A Simple Tutorial]

There are two ways of writing a one-liner for loop:

  • Method 1: If the loop body consists of one statement, simply write this statement into the same line: for i in range(10): print(i). This prints the first 10 numbers to the shell (from 0 to 9).
  • Method 2: If the purpose of the loop is to create a list, use list comprehension instead: squares = [i**2 for i in range(10)]. The code squares the first ten numbers and stores them in the array list squares.

Let’s have a look at both variants in more detail in the following article:

Related article: Python One Line For Loop [A Simple Tutorial]

Python Iterate Array One Line

How to iterate over an array in a single line of code?

Say, you’ve given an array (list) lst and you want to iterate over all values and do something with them. You can accomplish this using list comprehension:

lst = [1, 2, 3]
squares = [i**2 for i in lst]
# [1, 4, 9]

You iterate over all values in the array lst and calculate their square numbers. The result is stored in a new array list squares.

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:

[print(i**2) for i in lst]

Related article: List Comprehension Full Introduction

Python Fill Array One Line

Do you want to fill or initialize an array with n values using only a single line of Python code?

To fill an array with an integer value, use the list multiplication feature:

array = [0] * 10
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

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—for example, [None] * 10 creates a list of ten None elements.

Python Initialize Array One Line

How to Create a Python List?

There are many ways of creating an array (list) in Python. Let’s get a quick overview in the following table:

[]Square bracket: Initializes an empty list with zero elements. You can add elements later.
[x1, x2, x3, … ]List display: Initializes an empty list with elements x1, x2, x3, … For example, [1, 2, 3] creates a list with three integers 1, 2, and 3.
[expr1, expr2, ... ]List display with expressions: Initializes a list with the result of the expressions expr1, expr2, … For example, [1+1, 2-1] creates the list [2, 1].
[expr for var in iter]List comprehension: applies the expression expr to each element in an iterable.
list(iterable)List constructor that takes an iterable as input and returns a new list.
[x1, x2, ...] * nList multiplication creates a list of n concatenations of the list object. For example [1, 2] * 2 == [1, 2, 1, 2].

You can play with some examples in our interactive Python shell:

Exercise: Use list comprehension to create a list of square numbers.

Let’s dive into some more specific ways to create various forms of lists in Python.

Related Article: How to Create a Python List?

Python Filter Array One Line

How can you filter an array in Python using an arbitrary condition?

How to Filter a List in Python?

The most Pythonic way of filtering an array is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering criterion.

For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.

Here are three examples of filtering a list:

  • Get elements smaller than eight: [x for x in lst if x<8].
  • Get even elements: [x for x in lst if x%2==0].
  • Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1]

# Filter all elements <8
small = [x for x in lst if x<8]

# Filter all even elements
even = [x for x in lst if x%2==0]

# Filter all odd elements
odd = [x for x in lst if x%2]

The output is:

# Elements <8
[2, 6, 4, 3, 1]

# Even Elements
[8, 2, 6, 4]

# Odd Elements
[3, 1]

This is the most efficient way of filtering an array and it’s also the most Pythonic one.

Related Article: How to Filter a List in Python?

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • 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
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!