stewart Gauld

1671119037

Create Video Ads with Canva in minutes

Create Video Ads with Canva in minutes | Video Ad Maker (2023)

The aim of this tutorial is to guide you through how to create video ads with Canva using their free video maker so you can get started with powerful video marketing for your small business!

Video marketing is an integral part of any marketing strategy for all types and sizes of business, however for small businesses it can sometimes be a daunting and expensive process to create video content (like video ads).

This is where Canva’s free video maker becomes an ideal solution.

You can simply create free video content in minutes!

If you haven’t heard of Canva before, you’re missing out!

They are a leading (and free) online design and graphic design platform that lets you easily create posters, logos, presentations, social media content, and more for your small business.

If you’d like to learn more about how to use Canva, check out this video tutorial that walks you through step-by-step how to use Canva to create stunning designs!

 

How to create Video Ads with Canva?

In this Canva tutorial, we’re going to share how to create video ads for free in minutes with Canva’s video maker and video editor.

Let’s go ahead and dive into this free video maker tutorial so you can start creating dynamic video ads for your business with Canva!

 

1. Getting Started With The Canva Video Maker

Getting Started With The Canva Video Maker

Get started with Canva for FREE here

 *The link above is an affiliate link, which means we will get a commission if you upgrade to a paid plan (with no extra cost to you). This helps support our education-based website and we thank you in advance!

Firstly, you’ll need to sign into your Canva account on your website browser.

If you’re new to Canva, you’ll need to sign up and create an account for free. To sign up for Canva:

Let’s meet you inside your account and start creating video ads with Canva using their free video maker!

It’s important to note that during this Canva video maker tutorial, we’re using a paid Canva Pro account.

However, as this is a tutorial focusing on how to create video ads for free, we’ll point out the differences between the Free plan and the paid Pro Plan while navigating around so that you can understand the differences between a paid and free Canva plan.

There are actually a few ways that you can quickly start creating video ads with Canva (or any other type of video content).

We’re going to delve into these below.

Read more: How To Create A Free Website with Canva

 

2. Choose a Custom Video Size

Choose a Custom Video Size

The first way that you can start creating video content within Canva is to choose a  custom video size.

  • Navigate over to the right-hand side of your Canva dashboard and click on ‘Custom size’.

You now have the option to add custom size to the template you want to use

  • Simply type in the size you want the width of your template to be under ‘Width’.
  • Type in the height under ‘Height’.

For example, if you wanted to create a template that’s square, you’d type in ‘500’ under the ‘Width’ field and ‘500’ in the ‘Height’ field.

This ‘Custom size’ option is ideal if you know exactly what size template you want to use.

However, for the purpose of this Canva video editor tutorial, we’re not going to choose this option.

Read more: Top 5 ways to create powerful business videos.

 

3. Video Templates

Video Templates

Next, we’ll show you how to create a Video ad with a template.

Firstly, you’ll need to search for a Video ad template by following the steps below:

  • Navigate over and click on the search bar in the middle of your dashboard showing the text ‘Search your content or Canva’s’.
  • Type in ‘Video ads’.

As you can see, Canva is going to generate some options that you can click on to use to create your video (see screengrab).

Some of these suggestions options include:

  • A YouTube video ad.
  • A Feed add video (a portrait video that you can use in your Facebook, Instagram, or TikTok stories)
  • A Pinterest video ad.
  • A Linkedin video ad.

However, for the purpose of this tutorial, we’re not going to choose those options. We’re going to check out some of the different templates Canva has to offer instead.

  • Navigate up to the search bar.
  • Hit enter.

3.1

One of the great things we love about Canva is you can simply use pre-made templates in order to create your own designs!

For the purpose of this tutorial on how to create video ads for free with Canva, we’ll choose a video ad template and then customize that template.

As you can see, there are over 3123 templates relating to ‘Video Ads’ that we can now simply view, choose and customize to our liking (see screengrab).

You can filter your template options over on the left-hand side. 

  • Select and deselect the categories, styles, themes, or colors you want to filter and show for your video ad template.

For the purpose of this free video maker tutorial, we’re going to create a video ad for a gym (see screengrab).

Go ahead and take the time to pick a template that best suits your business and brand. Once you’ve done that:

  • Simply go ahead and click on your chosen pre-made template.

Remember, you also have the option to create your video from scratch, however, if this is your first time creating a video with Canva or maybe you have very limited design and technical experience when it comes to crafting a video, then we suggest using pre-made templates.

3.2

Once you’ve chosen your team plate, you can actually see the size of your template.

  • Head up and click on ‘Resize’ in the top left-hand corner.

Our chosen template is going to be ideal for many different types of platforms.

With Canva Pro (the paid plan), you can actually change the size of your designs at any stage.

However, with the free plan, you can’t access this feature of resizing your designs.

Read more: How To Create QR Codes for FREE

 

4. Your Design Canvas

Your Design Canvas

Here you can see that we have the template that we selected (see screengrab).

Our template is made up of different scenes, and each scene is made up of many different elements that you can simply click on and customize.

We’ll talk more about customizing each of these elements shortly, however, let’s continue with this tutorial to create video ads with Canva!

Read more: How To Create Videos for Your Business

 

5. Change The Video Template

Change The Video Template

 You can easily change your video templates if you’re not happy with the one selected.

  • Navigate over to the left-hand sidebar to ‘Templates’.
  • Type in a specific video template keyword in the search bar related to the type of design or video that you’re after.

Because we’re creating a video ad for a gym, we’re going to go ahead and type in ‘Gym’.

Once you’ve typed in your keyword:

  • You’ll notice some suggested keywords underneath the search bar that you can also click on and use to find specific templates.
  • Underneath these, you’ll see all the available templates relating to that keyword.

It’s important to note that some templates are only available on the ‘Pro’ paid plan.

You can identify these by hovering over each template.

If they have a crown icon and the word ‘Pro’, it means they are only available on the Pro paid plan.

We’ll go ahead and choose a free template to get stuck on how to create video ads with Canva for free!

 

6. Video Structure

Video Structure

Once you’ve chosen your template, Canva will give you the option to replace your existing template with different suggested pages.

This is a page here on the left-hand side (see screengrab).

Make sure that you consider each of your different pages when creating your video.

You can think about each of your pages as separate ‘scenes’ to your video.

This template has multiple different pages and different scenes that we want to add to our video, so we’re going to click ‘Apply all four pages’ on the left-hand side.

6.1

Once you click it will replace the existing template with the new 4 pages.

You can now see that our video consists of four separate pages (four separate scenes) (see screengrab).

Once you’ve added in your scenes, you can simply click on each scene to customize it.

Additionally, you can zoom in and out to have a better understanding of your video scenes. 

  • Head down underneath your scene thumbnails.
  • Simply click and drag on the zoom slider to adjust the zoom in or out (see screengrab).
  • Next to the zoom slider, click on the ‘Zoom thumbnails’ icon.

That’s going to allow you to actually zoom in or out to that particular scene and add finer details or small adjustments to your video elements.

  • Next to the ‘Zoom thumbnail’ icon, click on ‘Grid view’.

That’s going to generate a grid view of all your different videos 

  • Simply come down and turn off ‘Grid view’ to exit out of ‘Grid view’.

 

7. Edit Video Elements – Free Video Editor

Edit Video Elements - Free Video Editor

Now we’ll walk you through how to edit and customize your video elements within your scenes with Canva’s free video editor! Follow the steps to find out how:

First scene:

  • Click on the first scene of your video.

As you can see, we’re using a free template.

  • Navigate up to and click on one of the elements you want to edit.

We’ll use and click on our element ‘Max fit’ as an example.

Within this element, we have a title (Max fit), a logo next to the title, and a subtitle underneath (fitness training).

Each of these three items has been grouped (see screengrab).

If you’d like to ungroup your items within your elements to edit them individually:

  • Navigate up to the three dots next to ‘Animate’ above your scene.
  • Click on ‘Ungroup’.

This will allow you to edit each of these different elements separately.

7.1

Let’s say we want to replace and customize our title ‘Max fit’ with our own gym name.

  • Click on the ‘Max fit’ element.
  • Type in the new name. We’re going to rename our element ‘Level up Fitness’.

Our new name is quite long so it doesn’t quite fit within our element. To change the size of your element:

  • Simply click on the element and drag it out so it fits.
  • Resize your element by simply dragging out the corners of the element.

Above your scene, you also have a bunch of formatting options where you can edit your text (see screengrab).

Here you can:

  • Change the size
  • Change the font.
  • Change the color.
  • Change the alignment.
  • Make it a list.
  • Change the spacing.
  • Add a particular effect.

Next, we’ll show you how to replace an element within your scene.

We’ll go ahead and replace this logo with a different logo.

  • Navigate over to ‘Elements’ on the left-hand sidebar below ‘Templates’.
  • Type in your keyword in the search bar.

We’re going to type in ‘Gym’ again.

That’s going to generate all these different gym icons that you can now choose for your logo (see screengrab).

Alternatively, you can upload your own logo if you have one already. 

  • Navigate over to ‘Upload’ to upload your own logo.

You can actually also use Canva to create your own logo completely for free!

If you’re interested in learning how to create your own logo with Canva, you can check out our step-by-step beginners tutorial here.

However, let’s get back to this tutorial on how to create video ads for free with Canva.

For the purpose of this tutorial, we’re going to pick a logo from our search results.

We like the look of this logo here (see screengrab).

Once you’ve selected your chosen logo, click on the logo.

That will simply add your logo to your scene.

Now you’ll need to delete the original logo. 

  • Click on the logo you want to delete.
  • Click the rubbish bin icon.

To resize your new logo:

  • Select your new logo.
  • Drag and drop your logo to place it where you want within your scene.
  • Drag out the sides to the size that you like (like we showed you earlier).

Additionally, you can change the color of your logo. 

  • Navigate up to the color icon next to ‘Edit image’.
  • Simply click on the color you want. This will automatically change your logo color.

7.2

We’re going to change the color of our logo to white (see screengrab).

Next, we’re going to quickly go ahead and change our sub-text i.e ‘Fitness Training’ within our element using the same process as we showed you with our title.

However, we’re going to keep it as it is.

Within this scene, there’s a background video behind the elements we just edited.

To customize this video:

  • Click on the background image (video).
  • Navigate up to and click on the scissor icon to change the length of this particular video.

You can see the length of our video in the middle part (which is three seconds long).

  • Simply drag the middle part to make it longer or shorter if you’d like to change the length.
  • Click ‘Done’.
  • Click ‘Play’ on the scene to preview the video.

There’s also an animation for this video that we’ll show you soon when we give this scene a preview.

7.3

If you’d like to add a new video to your scene, follow these steps:

  • Navigate down to ‘Videos’ on the left-hand sidebar.
  • Type in your keyword again in the search bar.

We’re going to type in ‘Gym’ again.

That’s going to generate videos related to the keyword you typed in.

  • Navigate through these videos to pick the one you like.

For us, most of these are ‘Pro’ videos, which means you need to upgrade to a paid plan.

However, there are some free videos to choose from.

We’re going to choose a darker video to replace our original gym video.

Once you’ve found a video you want to replace your original video with:

  • Click on the new video
  • Drag and drop this video onto your scene.

That’s going to replace your video with the existing one

  • Navigate back up to the scissor icon.
  • Simply click on and drag your video to your preferred length if you want to change your video length.

We’re going to make this video ‘Three seconds’ again.

Once you’ve edited the length of your video:

  • Select ‘Done’.

To preview your video:

  • Simply navigate up to the top right-hand corner next to ‘Share’
  • Click here (see screengrab).

And that’s going to generate a full preview of your video where you can see all of your different scenes.

  • Navigate back over to ‘Close’ once you’ve finished previewing your video.

7.4

After previewing, you can again make more changes. For example, we’re going to make the video a bit longer.

  • Click back on the video you want to make longer.
  • Navigate up to the scissor icon again.
  • Drag your video out to your preferred length.

We’re going to double the length of the video, so we’ll drag ours out to six seconds.

You can also change the video section you want to capture.

  • Select the whole section that you want to change.
  • Drag the whole section out to where you want to capture it.
  • Click ‘Done’.

Again, you can click ‘Preview’ to preview your new video changes.

You can continue this process until you’re happy with your video length and the section of the video you want to capture.

7.5

Next, we’ll show you how to add an animation for different text elements. 

  • Navigate over to the text element you want to animate.

We’re going to pick ‘Level Up Fitness’ again.

  • Navigate up to and click on ‘Animate’.
  • All of your animation options will appear on the left-hand sidebar (see screengrab).
  • Simply click on each animation option to preview what it will look like for your text element.

We like the look of the ‘Block’ animation, so we’re going to click on ‘Block’.

  • Click ‘Block’.

Our title ‘Level up Fitness’ is now a block animation.

You can also change other elements to have the same or different animations.

We’re going to choose ‘Rise’ for our logo, and ‘Block’ for both our title and sub-text elements.

7.6

Second scene:

When you’re happy with your first scene, you can move on to the next scene to also customize it to your liking.

  • Simply navigate over to the next scene of your video down the bottom of the page (see screengrab).

Remember the next scene is the next page.

As you can see, we have our logo up that we deleted from the first scene (see screengrab).

To replace this logo with the new logo that you chose earlier:

  • Click on the logo element.
  • Simply click the rubbish bin icon.

7.7

  • Head back to the first scene.
  • Navigate up to and click on your logo.
  • Click on the three dots.
  • Click ‘Copy’.

7.8

  • Head back to the second scene.
  • Simply paste that logo where you want it to go.

We’re happy with that.

You can again resize your logo by dragging the different sides.

Once you’re happy with your logo, you can again move on to customizing the different elements within this scene using the same process as we showed you for the first scene.

You can then go ahead and preview your second scene video! 

  • Select the ‘play’ button on the video to ‘Preview’ to preview the video.

Make sure you time the time to go through each of your different scenes using this process above to customize each of your different scenes.

7.9

Third scene:

We will quickly go ahead and select our third scene to paste in our new logo (see screengrab) using the same process we showed you in our second scene, and again in our fourth scene.

7.10

Fourth scene:

As you can see in our fourth scene, if we click on these elements, you can see they have grouped together again (see screengrab). To ungroup these and add in our new logo:

  • Navigate up to the three dots next to your formatting options.
  • Select ‘Ungroup’.
  • Click on each of these elements.
  • Click the rubbish bin icon to delete an element.

7.11

  • Paste in your new logo again.
  • Drag your logo where you want it to go.

Let’s say you want to edit an element, however, the element is quite small and you can’t quite see it.

You can zoom in to get a closer look.

  • Head back down to the zoom slider.
  • Zoom in.

Next, let’s change our text to our own branding. (see screengrab).

  • Simply highlight the text you want to change and type in your own text.

We’re going to change ours from ‘Max Fit’ to ‘Level up Fitness’.

You can then move the element around or change the size to your liking using the same process as we explained in our first scene.

We’re happy with that

Once you’ve finished editing and changing you are zoomed in on the scene:

  • Come down and zoom back out for a more macro view to see how it looks.

From there, if you’re not quite happy with it you can continue to edit your scene either zoomed in or zoomed out.

However, we’re happy with our video.

Additionally, you can upload your own elements, images, or videos to add to your video.

  • Navigate over to the left-hand sidebar.
  • Click on ‘Uploads’.

For example, if we already owned a gym and had already taken our own video shots of people working out at our gym, we could upload these or replace the default template videos with our own shots.

7.12

To add in your own additional text element:

  • Click on ‘Text’ on the left-hand sidebar.

For example, we could add this header up here (see screengrab).

  • Navigate over to the font to change the font.
  • Simply type in what text you want to add in.

Because this is our last scene, we’re going to type in ‘Send us a message now for a one week free trial’ to add to our scene.

Again, you can simply:

  • Drag the corners of the element to change the size.
  • Click, drag and place the element to where you want it to go.
  • Navigate up to ‘Animate’ to add an animation to the text element.

We’re going to choose ‘Block’ again, however, you can choose any animation you like.

7.13

To edit a specific portion of your text element:

  • Highlight the portion of the text element you want to edit.

We’re going to highlight ‘7 day free trial’:

  • Click on the color icon (see screengrab) within the formatting options.
  • Select the color you want to change that specific text to.

We’ll choose yellow, then select the ‘italics’ icon to change the text to italics.

As you can see, we now have a call-to-action message that stands out.

These small detailed changes will help people see our message once they’ve finished watching the video (see screengrab).

To find and add particular photos to add to your video:

  • Navigate over to the left-hand sidebar.
  • Click on ‘Photos’.
  • Select a photo you want to add to your video (see screengrab).

If you’re not happy with the overall color scheme of your video, you can:

  • Navigate down to ‘Styles’ and select another color scheme of your choice.
  • You can also create your own brand kit color scheme (see screengrab).

This means you can change the color (the entire color) of your video elements.

Below ‘Styles’, you have ‘Videos’ again.

This is where you can replace videos (which we’ve talked about).

Below that, you have ‘Background’, where you can simply replace the background.

  • Select ‘Background’.
  • Type in a keyword related to the type of background that you want to add to your video scene.

Lastly, you can add audio to your video. You can do this by:

  • Clicking ‘More’ down the bottom of the left-hand sidebar.
  • Locate ‘Audio’.

We currently have four scenes within our video. If you’d like to add more scenes from scratch:

  • Come down to the bottom of the screen to view your scene thumbnails.
  • Click the ‘+’ button next to your last scene or one of the ‘+’ buttons in between your scenes (see screengrab).

Once you’ve customized the video template that you selected, or once you’ve finished creating your video from scratch (depending on what route you took), you can preview your whole video.

  • Again click on the play button next to ‘Share’ in the upper right-hand corner.

That’s going to allow you to preview your whole video!

 

8. Share And Download

Share And Download

Once you’re previewed your whole video and are happy with it:

  • Navigate up to ‘Download’ in the right-hand corner within your preview (see screengrab) or
  • Simply navigate over to ‘Close’ in the left-hand corner within your preview.
  • Navigate over to ‘Share’ to share this video with people.

If you’ve added people to your Canva account, you can:

  • Type in their names to share this video with them (see screengrab).

 Alternatively:

  • Click ‘View-only link’ so that people can view this link.

We’re going to download this video.

  • Click ‘Download’.
  • Navigate up to ‘File type’.
  • Make sure that you have ‘MP4 video’ selected.
  • Come down and make sure ‘All pages’ are selected because you want to download the entire video.
  • Come down and click ‘Download’.

Give Canva a moment to create and download your new video ad! (see screengrab).

  • Click on ‘Copy’ to copy this link to share your video with anyone you like.
  • Navigate down to the bottom left-hand corner (see screengrab).

You have now downloaded your video ad!

You can now use this video ad across all the different channels and platforms that you use to promote your business.

Remember, Canva allows you to create any type of video ad that you can think of.

And that is how you can create video ads with Canva in minutes!

What is GEEK

Buddha Community

Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Tamale  Moses

Tamale Moses

1669003576

Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities

cities.append(‘Chennai’)

#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
	
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays

print(weekdays)

Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple

print(person)

Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple

print(person)

Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list

print(list1)

Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10
 

#printing the value of ‘x’

print(x)

Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(x)))

Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’

print(y)

Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(y)))

Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick checkPython Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.

FAQs

1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.


Original article source at: https://www.mygreatlearning.com

#python 

Shubham Ankit

Shubham Ankit

1657081614

How to Automate Excel with Python | Python Excel Tutorial (OpenPyXL)

How to Automate Excel with Python

In this article, We will show how we can use python to automate Excel . A useful Python library is Openpyxl which we will learn to do Excel Automation

What is OPENPYXL

Openpyxl is a Python library that is used to read from an Excel file or write to an Excel file. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, adding formulas, and more.

Workbook: A spreadsheet is represented as a workbook in openpyxl. A workbook consists of one or more sheets.

Sheet: A sheet is a single page composed of cells for organizing data.

Cell: The intersection of a row and a column is called a cell. Usually represented by A1, B5, etc.

Row: A row is a horizontal line represented by a number (1,2, etc.).

Column: A column is a vertical line represented by a capital letter (A, B, etc.).

Openpyxl can be installed using the pip command and it is recommended to install it in a virtual environment.

pip install openpyxl

CREATE A NEW WORKBOOK

We start by creating a new spreadsheet, which is called a workbook in Openpyxl. We import the workbook module from Openpyxl and use the function Workbook() which creates a new workbook.

from openpyxl
import Workbook
#creates a new workbook
wb = Workbook()
#Gets the first active worksheet
ws = wb.active
#creating new worksheets by using the create_sheet method

ws1 = wb.create_sheet("sheet1", 0) #inserts at first position
ws2 = wb.create_sheet("sheet2") #inserts at last position
ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position

#Renaming the sheet
ws.title = "Example"

#save the workbook
wb.save(filename = "example.xlsx")

READING DATA FROM WORKBOOK

We load the file using the function load_Workbook() which takes the filename as an argument. The file must be saved in the same working directory.

#loading a workbook
wb = openpyxl.load_workbook("example.xlsx")

 

GETTING SHEETS FROM THE LOADED WORKBOOK

 

#getting sheet names
wb.sheetnames
result = ['sheet1', 'Sheet', 'sheet3', 'sheet2']

#getting a particular sheet
sheet1 = wb["sheet2"]

#getting sheet title
sheet1.title
result = 'sheet2'

#Getting the active sheet
sheetactive = wb.active
result = 'sheet1'

 

ACCESSING CELLS AND CELL VALUES

 

#get a cell from the sheet
sheet1["A1"] <
  Cell 'Sheet1'.A1 >

  #get the cell value
ws["A1"].value 'Segment'

#accessing cell using row and column and assigning a value
d = ws.cell(row = 4, column = 2, value = 10)
d.value
10

 

ITERATING THROUGH ROWS AND COLUMNS

 

#looping through each row and column
for x in range(1, 5):
  for y in range(1, 5):
  print(x, y, ws.cell(row = x, column = y)
    .value)

#getting the highest row number
ws.max_row
701

#getting the highest column number
ws.max_column
19

There are two functions for iterating through rows and columns.

Iter_rows() => returns the rows
Iter_cols() => returns the columns {
  min_row = 4, max_row = 5, min_col = 2, max_col = 5
} => This can be used to set the boundaries
for any iteration.

Example:

#iterating rows
for row in ws.iter_rows(min_row = 2, max_col = 3, max_row = 3):
  for cell in row:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C3 >

  #iterating columns
for col in ws.iter_cols(min_row = 2, max_col = 3, max_row = 3):
  for cell in col:
  print(cell) <
  Cell 'Sheet1'.A2 >
  <
  Cell 'Sheet1'.A3 >
  <
  Cell 'Sheet1'.B2 >
  <
  Cell 'Sheet1'.B3 >
  <
  Cell 'Sheet1'.C2 >
  <
  Cell 'Sheet1'.C3 >

To get all the rows of the worksheet we use the method worksheet.rows and to get all the columns of the worksheet we use the method worksheet.columns. Similarly, to iterate only through the values we use the method worksheet.values.


Example:

for row in ws.values:
  for value in row:
  print(value)

 

WRITING DATA TO AN EXCEL FILE

Writing to a workbook can be done in many ways such as adding a formula, adding charts, images, updating cell values, inserting rows and columns, etc… We will discuss each of these with an example.

 

CREATING AND SAVING A NEW WORKBOOK

 

#creates a new workbook
wb = openpyxl.Workbook()

#saving the workbook
wb.save("new.xlsx")

 

ADDING AND REMOVING SHEETS

 

#creating a new sheet
ws1 = wb.create_sheet(title = "sheet 2")

#creating a new sheet at index 0
ws2 = wb.create_sheet(index = 0, title = "sheet 0")

#checking the sheet names
wb.sheetnames['sheet 0', 'Sheet', 'sheet 2']

#deleting a sheet
del wb['sheet 0']

#checking sheetnames
wb.sheetnames['Sheet', 'sheet 2']

 

ADDING CELL VALUES

 

#checking the sheet value
ws['B2'].value
null

#adding value to cell
ws['B2'] = 367

#checking value
ws['B2'].value
367

 

ADDING FORMULAS

 

We often require formulas to be included in our Excel datasheet. We can easily add formulas using the Openpyxl module just like you add values to a cell.
 

For example:

import openpyxl
from openpyxl
import Workbook

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']

ws['A9'] = '=SUM(A2:A8)'

wb.save("new2.xlsx")

The above program will add the formula (=SUM(A2:A8)) in cell A9. The result will be as below.

image

 

MERGE/UNMERGE CELLS

Two or more cells can be merged to a rectangular area using the method merge_cells(), and similarly, they can be unmerged using the method unmerge_cells().

For example:
Merge cells

#merge cells B2 to C9
ws.merge_cells('B2:C9')
ws['B2'] = "Merged cells"

Adding the above code to the previous example will merge cells as below.

image

UNMERGE CELLS

 

#unmerge cells B2 to C9
ws.unmerge_cells('B2:C9')

The above code will unmerge cells from B2 to C9.

INSERTING AN IMAGE

To insert an image we import the image function from the module openpyxl.drawing.image. We then load our image and add it to the cell as shown in the below example.

Example:

import openpyxl
from openpyxl
import Workbook
from openpyxl.drawing.image
import Image

wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
#loading the image(should be in same folder)
img = Image('logo.png')
ws['A1'] = "Adding image"
#adjusting size
img.height = 130
img.width = 200
#adding img to cell A3

ws.add_image(img, 'A3')

wb.save("new2.xlsx")

Result:

image

CREATING CHARTS

Charts are essential to show a visualization of data. We can create charts from Excel data using the Openpyxl module chart. Different forms of charts such as line charts, bar charts, 3D line charts, etc., can be created. We need to create a reference that contains the data to be used for the chart, which is nothing but a selection of cells (rows and columns). I am using sample data to create a 3D bar chart in the below example:

Example

import openpyxl
from openpyxl
import Workbook
from openpyxl.chart
import BarChart3D, Reference, series

wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active

values = Reference(ws, min_col = 3, min_row = 2, max_col = 3, max_row = 40)
chart = BarChart3D()
chart.add_data(values)
ws.add_chart(chart, "E3")
wb.save("MyChart.xlsx")

Result
image


How to Automate Excel with Python with Video Tutorial

Welcome to another video! In this video, We will cover how we can use python to automate Excel. I'll be going over everything from creating workbooks to accessing individual cells and stylizing cells. There is a ton of things that you can do with Excel but I'll just be covering the core/base things in OpenPyXl.

⭐️ Timestamps ⭐️
00:00 | Introduction
02:14 | Installing openpyxl
03:19 | Testing Installation
04:25 | Loading an Existing Workbook
06:46 | Accessing Worksheets
07:37 | Accessing Cell Values
08:58 | Saving Workbooks
09:52 | Creating, Listing and Changing Sheets
11:50 | Creating a New Workbook
12:39 | Adding/Appending Rows
14:26 | Accessing Multiple Cells
20:46 | Merging Cells
22:27 | Inserting and Deleting Rows
23:35 | Inserting and Deleting Columns
24:48 | Copying and Moving Cells
26:06 | Practical Example, Formulas & Cell Styling

📄 Resources 📄
OpenPyXL Docs: https://openpyxl.readthedocs.io/en/stable/ 
Code Written in This Tutorial: https://github.com/techwithtim/ExcelPythonTutorial 
Subscribe: https://www.youtube.com/c/TechWithTim/featured 

#python 

Sagar Shende

Sagar Shende

1586924505

How to implement Rewarded Video Ads in Flutter | Flutter Admob Tutorial

In this tutorial, we will Learn About how to implement Rewarded Video Ads in a flutter. Because Rewarded video is a way for developers to integrate ads into the app. Consumers can choose to watch them in replacement for points, lives, or virtual goods.

Github Code: https://alltechsavvy.com/rewarded-video-ads-in-flutter/

How to implement a Rewarded Video Ads in Flutter

Github Profile: https://github.com/sagarshende23

Part 1 Video
Flutter - How to Add ads to Flutter App:
https://youtu.be/2sLAcHDfbcQ
Part 2 Video
How to Add AdMob Real Ads in FlutterApp:
https://youtu.be/PxYiLDuS3hk
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
How to Implement Facebook Ads in Flutter: https://youtu.be/4tZhGP4LIVw

How To Integrate Firebase into Flutter: https://youtu.be/M_fI_fZ-XSs

How to Integrate Google Sign-in into Flutter app(Part 1): https://youtu.be/bh3rBWnMjzk

How to Integrate Google Sign-in into Flutter app(Part 2): https://youtu.be/5HEKQs_Lgp4

How to Implement Online & Offline Connectivity: https://youtu.be/mWfarKw6_UA

Check out our Website for more Flutter Tutorials
https://alltechsavvy.com/

#rewarded video ads #rewarded video ads flutter #video ads #flutter video ads

田辺  亮介

田辺 亮介

1662351030

Python中最常用的數據結構

在任何編程語言中,我們都需要處理數據。現在,我們需要處理數據的最基本的事情之一就是以有組織的方式有效地存儲、管理和訪問它,以便我們可以在需要時將其用於我們的目的。數據結構用於滿足我們所有的需求。

什麼是數據結構?

數據結構是編程語言的基本構建塊。它旨在提供一種系統的方法來滿足本文前面提到的所有要求。Python 中的數據結構是List、Tuple、Dictionary 和 Set。它們被視為Python 中的隱式或內置數據結構。我們可以使用這些數據結構並對它們應用多種方法來管理、關聯、操作和利用我們的數據。

我們還有用戶定義的自定義數據結構,即StackQueueTreeLinked ListGraph。它們允許用戶完全控制其功能並將其用於高級編程目的。但是,我們將專注於本文的內置數據結構。

隱式數據結構 Python

隱式數據結構 Python

列表

列表幫助我們以多種數據類型順序存儲數據。它們類似於數組,除了它們可以同時存儲不同的數據類型,如字符串和數字。列表中的每個項目或元素都有一個指定的索引。由於Python 使用基於 0 的索引,因此第一個元素的索引為 0,並且繼續計數。列表的最後一個元素以 -1 開頭,可用於訪問從最後一個到第一個的元素。要創建一個列表,我們必須將項目寫在方括號內

關於列表要記住的最重要的事情之一是它們是可變的。這僅僅意味著我們可以通過使用索引運算符直接訪問它作為賦值語句的一部分來更改列表中的元素。我們還可以對列表執行操作以獲得所需的輸出。讓我們通過代碼來更好地理解列表和列表操作。

1. 創建列表

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

輸出

['p', 'r', 'o', 'b', 'e']

2. 訪問列表中的項目

#accessing the list 
 
#accessing the first item of the list
my_list[0]

輸出

'p'
#accessing the third item of the list
my_list[2]
'o'

3. 向列表中添加新項目

#adding item to the list
my_list + ['k']

輸出

['p', 'r', 'o', 'b', 'e', 'k']

4. 移除物品

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

輸出

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

輸出

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5.排序列表

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

輸出

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

輸出

['y', 'r', 'm', 'l', 'k']

6. 查找列表的長度

#finding the length of list
 
len(my_list)

輸出

5

元組

元組與列表非常相似,關鍵區別在於元組是 IMMUTABLE,與列表不同。一旦我們創建了一個元組或有一個元組,我們就不能改變它裡面的元素。但是,如果我們在元組中有一個元素,它本身就是一個列表,那麼我們只能在該列表中訪問或更改。要創建一個元組,我們必須在括號內寫入項目。像列表一樣,我們有類似的方法可以用於元組。讓我們通過一些代碼片段來理解使用元組。

1. 創建一個元組

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

輸出

('apple', 'banana', 'guava')

2. 從元組訪問項目

#accessing first element in tuple
 
my_tuple[1]

輸出

'banana'

3. 元組的長度

#for finding the lenght of tuple
 
len(my_tuple)

輸出

3

4. 將元組轉換為列表

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

輸出

list

5. 反轉元組

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

輸出

('guava', 'banana', 'apple')

6. 對元組進行排序

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

輸出

('apple', 'banana', 'guava')

7. 從元組中刪除元素

為了從元組中刪除元素,我們首先將元組轉換為列表,就像我們在上面的方法之一(第 4 點)中所做的那樣,然後遵循列表的相同過程,並顯式刪除整個元組,只需使用del聲明

字典

字典是一個集合,它只是意味著它用於存儲帶有某個鍵的值並提取給定鍵的值。我們可以將其視為一組鍵:值對 和字典中的每個都應該是唯一的,以便我們可以相應地訪問相應的

字典由包含鍵:值對的花括號 { }表示。字典中的每一對都以逗號分隔。字典中的元素是無序的,當我們訪問或存儲它們時,序列並不重要。

它們是可變的,這意味著我們可以在字典中添加、刪除或更新元素。以下是一些代碼示例,可以更好地理解 python 中的字典。

需要注意的重要一點是,我們不能將可變對像用作字典中的鍵。因此,列表不允許作為字典中的鍵。

1. 創建字典

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

這裡,整數是字典的鍵,與整數相關的城市名稱是字典的值。

2. 從字典中訪問項目

#access an item
 
print(my_dict[1])

輸出

'Delhi'

3. 字典的長度

#length of the dictionary
 
len(my_dict)

輸出

3

4. 對字典進行排序

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

輸出

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. 在字典中添加元素

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6.從字典中刪除元素

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

Set 是 python 中的另一種數據類型,它是一個沒有重複元素的無序集合。集合的常見用例是刪除重複值並執行成員資格測試。花括號set()函數可用於創建集合。要記住的一件事是,在創建空集時,我們必須使用set(),。後者創建一個空字典。 not { }

以下是一些代碼示例,可幫助您更好地理解 Python 中的集合。

1. 創建一個 集合

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

輸出

{'apple', 'strawberry', 'mango'}

2. 訪問集合中的項目

#to test for an element inside the set
 
"apple" in my_set

輸出

True

3. 集合的長度

print(len(my_set))

輸出

3

4. 對集合進行排序

print(sorted(my_set))

輸出

['apple', 'mango', 'strawberry']

5. 在Set中添加元素

my_set.add("guava")
print(my_set)

輸出

{'apple', 'guava', 'mango', 'strawberry'}

6. 從 Set 中移除元素

my_set.remove("mango")
print(my_set)

輸出

{'apple', 'guava', 'strawberry'}

結論

在本文中,我們瀏覽了 Python 中最常用的數據結構,並了解了與它們相關的各種方法。

鏈接:https ://www.askpython.com/python/data

#python #datastructures