Sam  Son

Sam Son

1583481481

Using List Comprehensions in Python like Master

Many more people are starting to learn Python, as it has become one of the most popular programming languages for almost anything, like web development, scientific computing, and certainly artificial intelligence.

No matter where you’re going with Python, you unavoidably have to learn Python’s data structures, variable and function declarations, conditional statements, control flows, and other basic concepts.

One important “Pythonic” feature that can be puzzling to many beginners is the list comprehension—a concise way to create lists.

Heard of it before, but don’t know what it is?

Great, this article will provide you with a head-start for mastering list comprehensions in your Python learning adventure.

For the purpose of easier organization, I’ve listed nine things that we should know about list comprehensions, including its syntax and various use cases.

1. Basic Syntax

The most basic list comprehension has the following syntax.

As mentioned previously, it serves as a concise way of doing certain things, such as creating lists. The expanded form is usually expressed as a for loop, in which each item of the iterable runs certain operations as specified in the expression.

# list comprehension
[expression for item in iterable]

# expanded form
for item in iterable:
    expression

2. Create a List

It’s not surprising at all that the most popular usage is to create a list concisely.

Suppose that we don’t know list comprehensions, we’ll probably do something like the below when it comes to the creation of a list. To do that, first, we’ll declare an empty list. Second, in the for loop, we append each item to the list.

>>> pets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')
>>> uppercased_pets = []
>>> for pet in pets:
...     uppercased_pets.append(pet.upper())
... 
>>> uppercased_pets
['BIRD', 'SNAKE', 'DOG', 'TURTLE', 'CAT', 'HAMSTER']

As mentioned in the basic syntax section, we can “compress” the for loop statement into one line — using the list comprehension with just one line of code, we can conveniently create a list by iterating the original list.

>>> pets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')
>>> uppercased_pets = [pet.upper() for pet in pets]
>>> uppercased_pets
['BIRD', 'SNAKE', 'DOG', 'TURTLE', 'CAT', 'HAMSTER']

3. Conditional Statement for Filtering

Sometimes, when we use list comprehensions to create a list, we don’t want to include all of the items on the existing list.

In this case, we need a conditional statement to filter out the items in the existing list that don’t meet certain criteria. The corresponding list comprehension has the following syntax.

# list comprehension with a conditional statement
[expression for item in iterable if some_condition]
# expanded form
for item in iterable:
    if some_condition:
        expression

Here’s an example of this usage.

>>> primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
>>> squared_primes = [x*x for x in primes if x%10 == 3]
>>> squared_primes
[9, 169, 529]

If we have a more complicated evaluation of the condition, we can even use a function.

>>> def has_four_legs(pet):
...     return pet in ('pig', 'dog', 'turtle', 'hamster', 'cat')
... 
>>> pets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')
>>> four_legs_pets = [pet.capitalize() for pet in pets if has_four_legs(pet)]
>>> four_legs_pets
['Dog', 'Turtle', 'Cat', 'Hamster']

4. Conditional Assignment

Sometimes, we don’t want to filter out the items from the original list.

Instead, we want to evaluate the condition to determine which expression is used. The syntax and its usage are given below. The syntax is also explained below.

# basic syntax
[expression0 if some_condition else expression1 for item in iterable]
# syntax explained: compared to the list comprehension's basic syntax: [expression for item in iterable], we can thin about that (expression0 if some_condition else expression1) is a whole part that constitutes the expression in the general format
>>> max_value = 10
>>> numbers = (7, 9, 11, 4, 3, 2, 12)
>>> ceiling_numbers0 = [number if number <= max_value else max_value for number in numbers] 
>>> ceiling_numbers0
[7, 9, 10, 4, 3, 2, 10]
>>> ceiling_numbers1 = [(number if number <= max_value else max_value) for number in numbers]
>>> ceiling_numbers1
[7, 9, 10, 4, 3, 2, 10]

5. Replace map()

In some situations, you may have seen people use map() to create a list. Specifically, the map() function has the following syntax together with an example of its basic usage.

One thing to note is that the map() function returns an iterable object, and thus we can use the list() function to generate a list from this iterable.

# map() returns an iterator object
map(function, iterable)
>>> pets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')
>>> uppercased_pets = list(map(str.upper, pets))
>>> uppercased_pets
['BIRD', 'SNAKE', 'DOG', 'TURTLE', 'CAT', 'HAMSTER']

As shown previously, we can replace the map() function with the list comprehension.

>>> pets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')
>>> uppercased_pets = [pet.upper() for pet in pets]
>>> uppercased_pets
['BIRD', 'SNAKE', 'DOG', 'TURTLE', 'CAT', 'HAMSTER']

6. Nested List Comprehensions

Suppose that we have a tuple in the code snippet below, and we want to create a new list of items that are squares of all numbers in the tuple.

In this case, we can use the nested list comprehension, the syntax of which is also shown below.

# basic syntax of the nested list comprehensions
[expression for sublist in outer_list for item in sublist]
# expanded form
for sublist in outer_list:
    for item in sublist:
        expression
>>> nested_numbers = ((1, 4, 7, 8), (2, 3, 5))
>>> squares = [x*x for numbers in nested_numbers for x in numbers]
>>> squares
[1, 16, 49, 64, 4, 9, 25]

Although it’s technically possible to have multiple levels for the nested list comprehensions, for readability, it’s not recommended to have more than two levels.

7. Use Walrus Operator

One of the new features in Python 3.8 is the introduction of the walrus operator (:=), which is used in assignment expression.

Suppose that we want to draw ten times from a list of letters, and the list that we’re creating will only include vowels from these drawings. Here’s how we can do it using the walrus operator in the list comprehension.

Specifically, in the example below, we evaluate whether a random letter drawn from the letters is a vowel, and if it is, it’ll be assigned to the letter to which the list comprehension’s expression can have access.

>>> letters = list('this is to produce a list of letters')
>>> letters
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 't', 'o', ' ', 'p', 'r', 'o', 'd', 'u', 'c', 'e', ' ', 'a', ' ', 'l', 'i', 's', 't', ' ', 'o', 'f', ' ', 'l', 'e', 't', 't', 'e', 'r', 's']
>>> import random
>>> vowels = [letter.upper() for _ in range(0, 10) if (letter := random.choice(letters)) in list('aeoui')]
>>> vowels
['I', 'O', 'O', 'O', 'O']

8. Set Comprehension

Although the list comprehension is known to many people, we can also use comprehension when we create a set. The basic syntax and its usage are shown below.

One major difference is that we use curly braces instead of square brackets. Certainly, by design, the elements in a set won’t have duplicates as opposed to a list where duplicates are allowed.

Please note that we can also use a conditional statement in a set comprehension.

# syntax for set comprehension
{expression for item in iterable}
>>> numbers = (1, 34, 5, 8, 10, 12, 3, 90, 70, 70, 90)
>>> unique_even_numbers = {number for number in numbers if number%2 == 0}
>>> unique_even_numbers
{34, 70, 8, 10, 12, 90}

9. Dict Comprehension

We have list and set comprehensions, and you won’t be surprised to learn that Python also has dict comprehension. The basic syntax and its usage are shown in the following code snippet.

# syntax for dict comprehension
{key_expression : value_expression for item in iterable}
>>> words = ('python', 'is', 'a', 'big', 'snake')
>>> len_words = {word : len(word) for word in words}
>>> len_words
{'python': 6, 'is': 2, 'a': 1, 'big': 3, 'snake': 5}
>>> len_words_p = {word : len(word) for word in words if word.startswith('p')}
>>> len_words_p
{'python': 6}

Conclusion

This article reviews the basic syntax of list comprehensions and their usage in various scenarios.

Beyond the list comprehension, we also talked about the set and dict comprehensions. These comprehensions allow us to create these basic collection data types very conveniently in Python with better readability.

Thank you for reading!

#python #Data Science #programming #development

What is GEEK

Buddha Community

Using List Comprehensions in Python like Master
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

August  Larson

August Larson

1624429860

How to Convert Loops to List Comprehension in Python

Do the same but faster

List comprehension is used for creating lists based on iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops.

The syntax of a list comprehension is actually easy to understand. However, when it comes to complex and nested operations, it might get a little tricky to figure out how to structure a list comprehension.

In such cases, writing the loop version first makes it easier to write the code for the list comprehension. We will go over several examples that demonstrate how to convert a loop-wise syntax to a list comprehension.

Basic structure of list comprehension (image by author)

Let’s start with a simple example. We have a list of 5 integers and want to create a list that contains the squares of each item. Following is the for loop that performs this operation.

lst_a = [1, 2, 3, 4, 5]

lst_b = []
for i in lst_a:
   lst_b.append(i**2)
print(lst_b)
[1, 4, 9, 16, 25]

#python #programming #how to convert loops to list comprehension in python #convert loops #list comprehension #how to convert loops to list comprehension

HI Python

HI Python

1640973720

Beyonic API Python Example Using Flask, Django, FastAPI

Beyonic API Python Examples.

The beyonic APIs Docs Reference: https://apidocs.beyonic.com/

Discuss Beyonic API on slack

The Beyonic API is a representational state transfer, REST based application programming interface that lets you extend the Beyonic dashboard features into your application and systems, allowing you to build amazing payment experiences.

With the Beyonic API you can:

  • Receive and send money and prepaid airtime.
  • List currencies and networks supported by the Beyonic API.
  • Check whether a bank is supported by the Beyonic API.
  • View your account transactions history.
  • Add, retrieve, list, and update contacts to your Beyonic account.
  • Use webhooks to send notifications to URLs on your server that when specific events occur in your Beyonic account (e.g. payments).

Getting Help

For usage, general questions, and discussions the best place to go to is Beyhive Slack Community, also feel free to clone and edit this repository to meet your project, application or system requirements.

To start using the Beyonic Python API, you need to start by downloading the Beyonic API official Python client library and setting your secret key.

Install the Beyonic API Python Official client library

>>> pip install beyonic

Setting your secrete key.

To set the secrete key install the python-dotenv modeule, Python-dotenv is a Python module that allows you to specify environment variables in traditional UNIX-like “.env” (dot-env) file within your Python project directory, it helps us work with SECRETS and KEYS without exposing them to the outside world, and keep them safe during development too.

Installing python-dotenv modeule

>>> pip install python-dotenv

Creating a .env file to keep our secrete keys.

>>> touch .env

Inside your .env file specify the Beyonic API Token .

.env file

BEYONIC_ACCESS_KEY = "enter your API "

You will get your API Token by clicking your user name on the bottom left of the left sidebar menu in the Beyonic web portal and selecting ‘Manage my account’ from the dropdown menu. The API Token is shown at the very bottom of the page.

getExamples.py

import os 
import beyonic
from dotenv import load_dotenv 

load_dotenv()

myapi = os.environ['BEYONIC_ACCESS_KEY']

beyonic.api_key = myapi 

# Listing account: Working. 
accounts = beyonic.Account.list() 
print(accounts)


#Listing currencies: Not working yet.
'''
supported_currencies = beyonic.Currency.list()
print(supported_currencies)

Supported currencies are: USD, UGX, KES, BXC, GHS, TZS, RWF, ZMW, MWK, BIF, EUR, XAF, GNF, XOF, XOF
'''

#Listing networks: Not working yet.
"""
networks = beyonic.Network.list()
print(networks)
"""

#Listing transactions: Working. 
transactions = beyonic.Transaction.list()
print(transactions) 

#Listing contact: Working. 
mycontacts = beyonic.Contact.list() 
print(mycontacts) 


#Listing events: Not working yet.
'''
events = beyonic.Event.list()
print(events)

Error: AttributeError: module 'beyonic' has no attribute 'Event'
'''

Docker file

FROM python:3.8-slim-buster

COPY . .

COPY ./requirements.txt ./requirements.txt

WORKDIR .

RUN pip install -r requirements.txt

CMD [ "python3", "getExamples.py" ]

Build docker image called demo

>>> docker build -t bey .

Run docker image called demo

>>>docker run -t -i bey 

Now, I’ll create a Docker compose file to run a Docker container using the Docker image we just created.


version: "3.6"
services:
  app:
    build: .
    command: python getExamples.py
    volumes:
      - .:/pythonBeyonicExamples

Now we are going to run the following command from the same directory where the docker-compose.yml file is located. The docker compose up command will start and run the entire app.


docker compose up

Output

NB: The screenshot below might differ according to your account deatils and your transcations in deatils.

docker compose up preview

To stop the container running on daemon mode use the below command.

docker compose stop

Output

docker compose preview

Contributing to this repository. All contributions, bug reports, bug fixes, enhancements, and ideas are welcome, You can get in touch with me on twitter @HarunMbaabu.

Download Details:
Author: HarunMbaabu
Source Code: https://github.com/HarunMbaabu/BeyonicAPI-Python-Examples
License: 

#api #python #flask #django #fastapi 

Osiki  Douglas

Osiki Douglas

1622279504

List Comprehension

List comprehension is nothing but a shorter and crisper version of the code and also memory efficient. By using this we can either create a new list or perform some operation in an existing list.

The normal code for creating a list of 0–9 will be like

x=[]
for i in range (10):
x.append(i)
print(x)
[0,1,2,3,4,5,6,7,8,9]

By using list comprehension

x=[i for i in range(10)]
print(x)

[0,1,2,3,4,5,6,7,8,9]

As you can see the normal code is long but the code that we did using list comprehension does the job just in one line so list comprehension is preferred over the traditional method.

#list-comprehension #lists #python #python-list-comprehension