Ikram Mihan

Ikram Mihan

1588389240

Difference Between append() and extend() | Python List

If you want to learn how to work with .append() and .extend() and understand their differences, then you have come to the right place. They are powerful list methods that you will definitely use in your Python projects.

In this article, you will learn:

  • How and when to use the .append() method.
  • How and when to use the .extend() method.
  • Their main differences.

Append

Let’s see how the .append() method works behind the scenes.

Use Cases

You should use this method when you want to add a single item to the end of a list.

Tips: You can add items of any data type since lists can have elements of different data types.

Syntax and Arguments

To call the .append() method, you will need to use this syntax:

From Left to Right:

  • The list that will be modified. This is usually a variable that references a list.
  • A dot, followed by the name of the method .append().
  • Within parentheses, the item that will be added to the end of the list.

Tips: The dot is very important. This is called “dot notation”. The dot basically says “call this method on this particular list”, so the effect of the method will be applied to the list that is located before the dot.

Examples

Here’s an example of how to use .append():

# Define the list
>>> nums = [1, 2, 3, 4]

# Add the integer 5 to the end of the existing list
>>> nums.append(5)

# See the updated value of the list
>>> nums
[1, 2, 3, 4, 5]

Tips: When you use .append() the original list is modified. The method does not create a copy of the list – it mutates the original list in memory.

Let’s pretend that we are conducting a research and that we want to analyze the data collected using Python. We need to add a new measurement to the existing list of values.

How do we do it? We use the .append() method!

You can see it right here:

# Existing list
>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]

# Add the float (decimal number) to the end of the existing list
>>> nums.append(7.34)

# See the updated value of the list
>>> nums
[5.6, 7.44, 6.75, 4.56, 2.3, 7.34]

Equivalent to…

If you are familiar with string, list, or tuple slicing, what .append() really does behind the scenes is equivalent to:

a[len(a):] = [x]

With this example, you can see that they are equivalent.

Using .append():

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]
>>> nums.append(4.52)
>>> nums
[5.6, 7.44, 6.75, 4.56, 2.3, 4.52]

Using list slicing:

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]
>>> nums[len(nums):] = [4.52]
>>> nums
[5.6, 7.44, 6.75, 4.56, 2.3, 4.52]

Appending a Sequence

Now, what do you think about this example? What do you think will be output?

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]
>>> nums.append([5.67, 7.67, 3.44])
>>> nums
# OUTPUT?

Are you ready? This will be the output:

[5.6, 7.44, 6.75, 4.56, 2.3, [5.67, 7.67, 3.44]]

You might be asking, why was the full list added as a single item? It’s because the .append() method adds the entire item to the end of the list. If the item is a sequence such as a list, dictionary, or tuple, the entire sequence will be added as a single item of the existing list.

Here we have another example (below). In this case, the item is a tuple and it is added as a single item of the list, not as individual items:

>>> names = ["Lulu", "Nora", "Gino", "Bryan"]
>>> names.append(("Emily", "John"))
>>> names
['Lulu', 'Nora', 'Gino', 'Bryan', ('Emily', 'John')]

Extend

Now let’s dive into the functionality of the .extend() method.

Use Cases

You should use this method if you need to append several items to a list as individual items.

Let me illustrate the importance of this method with a familiar friend that you just learned: the .append() method. Based on what you’ve learned so far, if we wanted to add several individual items to a list using .append(), we would need to use .append() several times, like this:

# List that we want to modify
>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]

# Appending the items
>>> nums.append(2.3)
>>> nums.append(9.6)
>>> nums.append(4.564)
>>> nums.append(7.56)

# Updated list
>>> nums
[5.6, 7.44, 6.75, 4.56, 2.3, 2.3, 9.6, 4.564, 7.56]

I’m sure that you are probably thinking that this would not be very efficient, right? What if I need to add thousands or millions of values? I cannot write thousands or millions of lines for this simple task. That would take forever!

So let’s see an alternative. We can store the values that we want to add in a separate list and then use a for loop to call .append() as many times as needed:

# List that we want to modify
>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]

# Values that we want to add
>>> new_values = [2.3, 9.6, 4.564, 7.56]

# For loop that is going to append the value
>>> for num in new_values:
	nums.append(num)

# Updated value of the list
>>> nums
[5.6, 7.44, 6.75, 4.56, 2.3, 2.3, 9.6, 4.564, 7.56]

This is more efficient, right? We are only writing a few lines. But there is an even more efficient, readable, and compact way to achieve the same purpose: .extend()!

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3]
>>> new_values = [2.3, 9.6, 4.564, 7.56]

# This is where the magic occurs! No more for loops
>>> nums.extend(new_values)

# The list was updated with individual values
>>> nums
[5.6, 7.44, 6.75, 4.56, 2.3, 2.3, 9.6, 4.564, 7.56]

Let’s see how this method works behind the scenes.

Syntax and Arguments

To call the .extend() method, you will need to use this syntax:

From Left to Right:

  • The list that will be modified. This is usually a variable that refers to the list.
  • A dot . (So far, everything is exactly the same as before).
  • The name of the method extend. (Now things start to change…).
  • Within parentheses, an iterable (list, tuple, dictionary, set, or string) that contains the items that will be added as individual elements of the list.

Tips: According to the Python documentation, an iterable is defined as “an object capable of returning its members one at a time”. Iterables can be used in a for loop and because they return their elements one at a time, we can “do something” with each one of them, one per iteration.

Behind the Scenes

Let’s see how .extend() works behind the scenes. Here we have an example:

# List that will be modified
>>> a = [1, 2, 3, 4]

# Sequence of values that we want to add to the list a
>>> b = [5, 6, 7]

# Calling .extend()
>>> a.extend(b)

# See the updated list. Now the list a has the values 5, 6, and 7
>>> a
[1, 2, 3, 4, 5, 6, 7]

You can think of .extend() as a method that appends the individual elements of the iterable in the same order as they appear.

In this case, we have a list a = [1, 2, 3, 4] as illustrated in the diagram below. We also have a list b = [5, 6, 7] that contains the sequence of values that we want to add. The method takes each element of b and appends it to list a in the same order.

Step 1. First element is appended.

Step 2. Second element appended.

Step 3. Third element appended

After this process is completed, we have the updated list a and we can work with the values as individual elements of a.

Tips: The list b used to extend list a remains intact after this process. You can work with it after the call to .extend(). Here is the proof:

>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6, 7]

# List b is intact!
>>> b
[5, 6, 7]

Examples

You may be curious to know how the .extend() method works when you pass different types of iterables. Let’s see how in the following examples:

For tuples:
The process works exactly the same if you pass a tuple. The individual elements of the tuple are appended one by one in the order that they appear.

# List that will be extended
>>> a = [1, 2, 3, 4]

# Values that will be added (the iterable is a tuple!)
>>> b = (1, 2, 3, 4)

# Method call
>>> a.extend(b)

# The value of the list a was updated
>>> a
[1, 2, 3, 4, 1, 2, 3, 4]

For sets:
The same occurs if you pass a set. The elements of the set are appended one by one.

# List that will be extended
>>> a = [1, 2, 3, 4]

# Values that will be appended (the iterable is a set!)
>>> c = {5, 6, 7}

# Method call
>>> a.extend(c)

# The value of a was updated
>>> a
[1, 2, 3, 4, 5, 6, 7]

For strings:
Strings work a little bit different with the .extend() method. Each character of the string is considered an “item”, so the characters are appended one by one in the order that they appear in the string.

# List that will be extended
>>> a = ["a", "b", "c"]

# String that will be used to extend the list
>>> b = "Hello, World!"

# Method call
>>> a.extend(b)

# The value of a was updated
>>> a
['a', 'b', 'c', 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

For dictionaries:
Dictionaries have a particular behavior when you pass them as arguments to .extend(). In this case, the keys of the dictionary are appended one by one. The values of the corresponding key-value pairs are not appended.

In this example (below), the keys are “d”, “e”, and “f”. These values are appended to the list a.

# List that will be extended
>>> a = ["a", "b", "c"]

# Dictionary that will be used to extend the list
>>> b = {"d": 5, "e": 6, "f": 7}

# Method call
>>> a.extend(b)

# The value of a was updated
>>> a
['a', 'b', 'c', 'd', 'e', 'f']

Equivalent to…

What .extend() does is equivalent to a[len(a):] = iterable. Here we have an example to illustrate that they are equivalent:

Using .extend():

# List that will be extended
>>> a = [1, 2, 3, 4]

# Values that will be appended
>>> b = (6, 7, 8)

# Method call
>>> a.extend(b)

# The list was updated
>>> a
[1, 2, 3, 4, 6, 7, 8]

Using list slicing:

# List that will be extended
>>> a = [1, 2, 3, 4]

# Values that will be appended
>>> b = (6, 7, 8)

# Assignment statement. Assign the iterable b as the final portion of the list a
>>> a[len(a):] = b

# The value of a was updated
>>> a
[1, 2, 3, 4, 6, 7, 8]

The result is the same, but using .extend() is much more readable and compact, right? Python truly offers amazing tools to improve our workflow.

Summary of their Differences

Now that you know how to work with .append() and .extend(), let’s see a summary of their key differences:

  • Effect: .append() adds a single element to the end of the list while .extend() can add multiple individual elements to the end of the list.
  • Argument: .append() takes a single element as argument while .extend() takes an iterable as argument (list, tuple, dictionaries, sets, strings).

I really hope that you liked my article and found it helpful, please share it with others!

Proficient and Efficient use Python Lists

You may also like: Proficient and Efficient use Python Lists

#python

What is GEEK

Buddha Community

Difference Between append() and extend() | Python List
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

Python Tips and Tricks for Competitive Programming

Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips:

  • **Converting a number into a List of digits using map() Function: **

Below is the implementation to convert a given number into a list of digits:

#competitive programming #python programs #python-itertools #python-library #python-list #python-list-of-lists #python-map

The anatomy of Python Lists

An easy guide to summarize the most common methods and operations regarding list manipulation in Python.

Python lists are a built-in type of data used to store items of any data type such as strings, integers, booleans, or any sort of objects, into a single variable.

Lists are created by enclosing one or multiple arbitrary comma-separated objects between square brackets.

Lists may contain elements of different data types

List items follows a sequenced or specific order

Access values by index

#python-programming #python #tutorial #list-manipulation #python-list #the anatomy of python lists

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 

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type