![]() |
|
[Tut] Python One Line Array - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python One Line Array (/thread-96935.html) |
[Tut] Python One Line Array - xSicKxBot - 08-28-2020 Python One Line Array 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:
Here’s the code: 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-->5Try It Yourself in Our Interactive Code Shell: https://repl.it/@finxter/pythonlistprint3?lite=true 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 Code: x if c else yCode: xCode: cCode: TrueCode: cCode: FalseCode: yHere’s a minimal example: Code: var = 21 if 3<2 else 42
# var == 42While you read through the article to boost your one-liner power, you can listen to my detailed video explanation: 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? There are two ways of writing a one-liner for loop:
https://trinket.io/embed/python/27248749cf 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) Code: lstCode: lst = [1, 2, 3]
squares = [i**2 for i in lst]
print(squares)
# [1, 4, 9]You iterate over all values in the array Code: lstCode: squaresYou 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: Code: [print(i**2) for i in lst] '''
1
4
9 '''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: Code: array = [0] * 10
print(array)
# [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, Code: [None] * 10Code: NonePython Initialize Array One Line There are many ways of creating an array (list) in Python. Let’s get a quick overview in the following table: Code | Description Code: []Square bracket: Initializes an empty list with zero elements. You can add elements later. Code: [x1, x2, x3, … ]List display: Initializes an empty list with elements Code: x1Code: x2Code: x3Code: [1, 2, 3]Code: [expr1, expr2, ... ]List display with expressions: Initializes a list with the result of the expressions Code: expr1Code: expr2Code: [1+1, 2-1]Code: [2, 1]Code: [expr for var in iter]List comprehension: applies the expression Code: exprCode: list(iterable)List constructor that takes an iterable as input and returns a new list. Code: [x1, x2, ...] * nList multiplication creates a list of n concatenations of the list object. For example Code: [1, 2] * 2 == [1, 2, 1, 2]You can play with some examples in our interactive Python shell: https://trinket.io/embed/python/c1e9402361 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? https://repl.it/@finxter/filterlistpython?lite=true The most Pythonic way of filtering an array is the list comprehension statement Code: [x for x in list if condition]Code: conditionCode: xFor example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement Code: [x for x in list if x<10]Here are three examples of filtering a list:
Code: lst = [8, 2, 6, 4, 3, 1] # Filter all elements <8
small = [x for x in lst if x<8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)The output is: Code: # 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 Python programmers will improve their computer science skills with these useful one-liners. ![]() Python One-Linerswill 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 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’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 Now!! |