You are reading the article Using Lambda Function With Amazon S3 updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Using Lambda Function With Amazon S3
Using Lambda Function with Amazon S3 Steps for Using AWS Lambda Function with Amazon S3To start using AWS Lambda with Amazon S3, we need the following −
Create S3 Bucket
Create role which has permission to work with s3 and lambda
Create lambda function and add s3 as the trigger.
ExampleLet us see these steps with the help of an example which shows the basic interaction between Amazon S3 and AWS Lambda.
User will upload a file in Amazon S3 bucket
Once the file is uploaded, it will trigger AWS Lambda function in the background which will display an output in the form of a console message that the file is uploaded.
The user will be able to see the message in Cloudwatch logs once the file is uploaded.
The block diagram that explains the flow of the example is shown here −
Creating S3 BucketLet us start first by creating a s3 bucket in AWS console using the steps given below −
Step 1 Step 2 Step 3 Step 4 Step 5Thus, we are done with bucket creation in S3.
Create Role that Works with S3 and LambdaTo create role that works with S3 and Lambda, please follow the Steps given below −
Step 1Go to AWS services and select IAM as shown below −
Step 2 Step 3 Step 4 Step 5Observe that we have chosen the following permissions −
Observe that the Policies that we have selected are AmazonS3FullAccess, AWSLambdaFullAccess and CloudWatchFullAccess.
Step 6Thus, our role named lambdawiths3service is created.
Create Lambda function and Add S3 TriggerIn this section, let us see how to create a Lambda function and add a S3 trigger to it. For this purpose, you will have to follow th Steps given below −
Step 1Go to AWS Services and select Lambda as shown below −
Step 2 Step 3Now let us add the S3 trigger.
Step 4Choose the trigger from above and add the details as shown below −
Step 5Select the bucket created from bucket dropdown. The event type has following details −
Select Object Created (All), as we need AWS Lambda trigger when file is uploaded, removed etc.
Step 6 Step 7You can find the the trigger display for the Lambda function as shown below −
Let’s add the details for the aws lambda function. Here, we will use the online editor to add our code and use nodejs as the runtime environment.
Step 8To trigger S3 with AWS Lambda, we will have to use S3 event in the code as shown below −
exports.handler = function(event, context, callback) { console.log("Incoming Event: ", event); const bucket = event.Records[0].s3.bucket.name; const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/+/g, ' ')); console.log(message); callback(null, message); };Note that the event param has the details of the S3event. We have consoled the bucket name and the file name which will get logged when you upload image in S3bucket.
Step 9Now, let us save the changes and test the lambda function with S3upload. The following are the code details added in AWS Lambda −
Step 10Now, let us add the role, memory and timeout.
Step 11Now, save the Lambda function. Open S3 from Amazon services and open the bucket we created earlier namely workingwithlambdaands3.
Upload the image in it as shown below −
Step 12 Step 13Thus, we have uploaded one image in our S3 bucket.
Step 14To see the trigger details, go to AWS service and select CloudWatch. Open the logs for the Lambda function and use the following code −
exports.handler = function(event, context, callback) { console.log("Incoming Event: ", event); const bucket = event.Records[0].s3.bucket.name; const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/+/g, ' ')); console.log(message); callback(null, message); };The output you can observe in Cloudwatch is as shown −
AWS Lambda function gets triggered when file is uploaded in S3 bucket and the details are logged in Cloudwatch as shown below −
Advertisements
You're reading Using Lambda Function With Amazon S3
How Parents() Function Works With Examples
Introduction to jQuery parents
Web development, programming languages, Software testing & others
Syntax:
$(selector ).parents(filter_expr)Or
$(selector).parents()In the above-given syntax, the jQuery parents() function is applied on a particular element. It is a selector tag where all ancestors are returned when this parent () function is applied to this selector tag. This function does not take any parameters, but still, it is considered optional.
selector: In this, the selector is nothing, but it is an HTML element or tag of which we want the element’s ancestors or grandparent element to be returned.
filter_expr: This is an optional parameter in this function for specifying the selector tag expression to look upwards in the DOM tree for searching with all this selector’s ancestors.
How parents() Function Works with Examples
In jQuery, the parents() function is a built-in function for displaying all the ancestors of the selected HTML tag for which this function needs to be applied. The working of this function is very simple Firstly, it will check for the specified selector tag, followed by the period (dot) operator and the parents() method to this selector tag. This function will traverse the entire DOM tree, where this tree is the representation of elements of the jQuery object.
Therefore parents() function traverses this DOM tree in the upward direction to search all the element’s ancestors such as grandparent element, great grandparent element, etc. are all displayed, which means this function parent () returns all the ancestor elements of the particular selected or matched HTML tag that is specified before the function declaration, and this particular specified selector optionally filters it. This function returns the element set in reverse order for the given multiple DOM having the original set, and the duplicate elements are removed and displayed.
Example #1Code:
.parents_func_body* { display: block; border: 2px solid red; color: red; padding: 5px; margin: 15px; } <script $(document).ready(function() { $(“p”).parents().css({ “color”: “blue”, “border”: “2px solid red” }); });
Output:
In the above example, we have first made the document ready for the web page to be displayed according to the given function in the above code. In this, we are using the .ready() function for making the document ready. Then we specify the parents() function in which “p” the paragraph tag as a selector for this function, which means this function returns all the ancestor elements of the element “P” in the above code. Finally, we are applying the .css() function to properly display each element with described properties. This logic is defined or declared within the script tag, which is within the head tag.
Example #2Now let us see another example for demonstrating the parents() function in which we are passing the optional parameters as some other HTML elements or selectors.
Code:
.main *{ border: 2px solid red; padding: 10px; margin: 10px; } function parents_func(){ $(document).ready(function(){ $(“p”).parents(“li, h2”).css({ “border”: “3px dashed blue”}); }); }
Conclusion – jQuery parentsIn this article, we conclude that the parents() function in jQuery is very simple and is used to search or traverse the DOM tree, which consists of various elements to find out the parent element to help any developer to easily correct or upgrade any details. Similar to this parent () function, which returns all its ancestors elements of any selected element, even the parent() function also returns the direct parent element but not all the ancestors elements.
Recommended ArticlesThis is a guide to jQuery parents. Here we discuss the introduction and how parents() function works with examples, respectively. You may also have a look at the following articles to learn more –
Getting Started With Your New Amazon Echo
Have you recently jumped on the bandwagon and purchased an Amazon Echo? If you’re like me, you’ve probably heard a lot of great things about the device and how a lot of people simply love their Echo!
Well, I decided to see what all the hype was about and got one for myself. I have to admit, the Echo is pretty fun to use and it’s really useful if you have kids around. My kids love asking it to play music and I’ve installed several skills so that they can play math games, word games, etc.
Table of Contents
In this article, I’m going to talk about how to quickly get your Echo setup and how to configure it so that you can get the most benefit from all of its current features. Amazon keeps adding new features to the Echo pretty much every week, so I’ll keep posting new articles when those new features make it to the device.
Setting Up an EchoWhen you get your Echo and unbox it, you’ll basically see three items inside: the Echo, the power adapter and some instructions. To get started, you start by plugging it into a wall outlet. While the device is booting up, you can go ahead and download the Amazon Alexa app from iTunes or the Google Play Store.
Once you download the app, go ahead and login with your Amazon account credentials.
Once you have signed in, go ahead and close the app and then check your Echo. By default, once it boots up, the ring that goes around the top should light up orange. This means it’s ready to start the WiFi setup process.
If, for some reason, the light is not orange, just press and hold the Action button for 5 seconds. The Action button is the one with just the single dot in the center. Now go to your phone and go to the WiFi settings section.
When the light is orange on the Echo, you should see an Amazon-WVM WiFi network that you can connect to. Once you connect to that network, go ahead and open the Alexa app on your device. It should automatically detect that you are trying to setup the device, but if not, tap the three horizontal lines at the top left, then tap on Settings and then tap on Set up a new device.
The setup screen should appear and it will remind you to make sure that the light ring is orange before continuing.
If everything is properly setup, you should see a Connected to Echo message on the next screen. Tap Continue to continue the setup.
On the next screen, you have to choose a WiFi network to connect your Echo to. This will be the WiFi network that your Echo connects to when it is powered on. Note that you can change the WiFi network or connect to additional networks later on using the app.
The next screen will show you a progress bar as your Echo is prepared.
Once everything is setup, you should be able to start talking to the Echo! When you open the app, you’ll see the Home screen gives you a tip and then just has one card telling you to customize Alexa.
The way the Echo works is that whenever you ask it something, it will respond via voice, but it will also create a card in the Alexa app that you will see on the home screen. For example, if you say “Alexa” and then say “What’s the weather like?“, it will tell you verbally, but it will also show the information in the app.
It’s kind of a history log of everything you have said to Alexa. To activate your Echo, you have to say the word “Alexa“. You can change this in the settings later if you like, but only to “Amazon” or “Echo“. That might change in the future, though.
Customizing AlexaThe first thing you probably want to do once the Echo is up and running is to train your voice so that it better understands you. To do this, go to the app, tap on the three lines at the top left, tap on Settings and then tap on Voice Training. It’s directly below the Set up a new device option I had mentioned towards the beginning of the article.
Once you have done that, you should configure your music, news, sports, calendar and traffic. To do all of that, go to Settings again and scroll down to the section that says Account.
These are all pretty easy to setup, so I won’t go into much detail. For Music & Media, you can play music from Amazon if you have Prime or Spotify, Pandora, iHeartRadio or TuneIn. Under Flash Briefing, you can configure a whole bunch of news programs like CNN, NPR, BBC, HuffPost, etc. Don’t go too crazy with this section though because your news briefing might end up being 40 minutes long!
Under Sports Update, just search for all your favorite teams and Alexa will give you an update on all of them when you ask. Traffic only allows you to enter a start and ending destination for now, so it is only good for people who commute everyday on the same route, i.e. home to work. Under Calendar, you can log into your Google Calendar and then use Alexa to add events to your calendar.
So what exactly do you say to activate all of these functions? Well, there are two ways to learn the commands. You can tap on the three lines at the top left and then tap on Things to Try or you can read all the commands online.
The other built-in features of Alexa are Timers & Alarms and Shopping & To-do lists. To set a timer, all you have to say is “Alexa, set a timer for x minutes.” For an alarm, just say “Alexa, set an alarm for 4 o’clock in the evening.” You can also say AM or PM if you like.
For the lists, just say “Alexa, add x to my shopping list” or “Alexa, add your-phrase to my to-do list.” Alexa, can also answer various questions like simple math or conversions. For facts, the device seems to rely on Wikipedia, so that’s either a good or bad thing, depending on who you ask. You can ask it things like “Who is the president of X country?” or “What is the capital of X state” or even something like “Name all of the continents”.
Alexa SkillsThe real power of Alexa, though, comes in the form of skills. If you tap on the three lines and then Skills, you’ll get a list of all the ways you can enhance the Echo. These are basically little apps written for the Echo by various companies or individuals.
There are a bunch of skills, but currently most of them are silly or useless. However, the list is getting better by the day and some are really good. For my kids, I use Baby Animals, Spelling Bee, Human Body Quiz, Mental Math, and Dinosaur Facts. I really like the Mental Math skill for my five-year old daughter.
For myself, I use the Capital One skill, This Day in History and Random World Facts. I also have the TP-LINK Kasa and SmartThings skills enabled so I can control my switches, etc. via Alexa. In a future post, I’ll write instructions on how to setup your Smart Home devices with Alexa.
Amazon Is Delaying Most Tech Shipments By About A Month, Even With Amazon Prime
Amazon is unfortunately pushing back the Amazon Prime shipping dates of many items, a consequence of its new priority on “essential” household goods.
Some Amazon tech products are delayed for weeksDig deep enough into the tech bins on Amazon’s site, and you’ll see listings like this dual-HDMI USB-C hubRemove non-product link, a perfect addition for a dual-display work-from-home setup. The hub, listed as in stock and Fulfilled by Amazon, will ship to Prime members in about a month, on Tuesday, April 21. That appears to be the case for many tech products across the site.
Amazon has been public about its challenges and its changes in priorities to address critical needs during the spread of coronavirus. An Amazon blog post from March 13 said, “we’ve changed our logistics, transportation, supply chain, purchasing, and third-party seller processes to prioritize stocking and delivering items that are a higher priority for our customers. This has resulted in some of our delivery promises being longer than usual.” A letter from Amazon CEO Jeff Bezos on March 21 defined more closely the kinds of items being prioritized: “essential items like household staples, sanitizers, baby formula, and medical supplies.”
Here are the tech products that Amazon is delayingA wide swath of work-from-home and DIY PC gear appears to be affected.
As we sampled Amazon’s listings, we began with the sort of tech gear you’d assume that would always be available: USB-C hubs, ethernet cables, HDMI cables, even an “Amazon’s Choice”-listed Seagate 2TB external hard driveRemove non-product link. At press time, all of the products we sampled from each category were scheduled to ship on April 21, just under a month out. And it’s not just peripherals: WD’s 1TB WD Blue internal SSDRemove non-product link also has been pushed out a month, even with Prime membership. Spinning internal hard drives like this WD 4TB NAS driveRemove non-product link are also subject to the same April 21 ship date, as are USB keys. Flash cards for digital cameras appear to be similarly affected.
We also found exceptions: Intel’s Core i7-9700Remove non-product link, in stock and available by this Thursday when we checked. The AMD Ryzen 5 1600Remove non-product linkwas also scheduled to ship by Friday.
Here’s what Amazon still has in stockIf you’re a parent working from home and you’ve discovered that your ancient laptop or Chromebook has given up the ghost, there’s good news: Quite a few, if not all of the laptops Amazon has for sale are available—they’ll just ship in about four days, not immediately.
A good example is this popular Acer Aspire 5Remove non-product link: it’s currently scheduled to ship by March 27. The bad news is that they’re still being snapped up; in the Acer Aspire example, the Ryzen 5 and Ryzen 7 versions are listed as being out of stock. (Don’t despair: this second Aspire 5Remove non-product link has a 10th-gen Intel Core chip inside for not much more, and it’s still on track to arrive within four days.)
Chromebooks appear to be under a bit more pressure, with ship dates pushing out to next week in some cases. For example, this Lenovo 11.6-inch ChromebookRemove non-product link will ship as late as April 1. It also appears to be fairly common to find popular Chromebooks, like the ASUS C100PA-DB01 Chromebook FlipRemove non-product link, available only via third-party sellers.
Here’s where to look for tech gear right now
A year ago, Amazon’s efficient supply chain meant that they could ship everything to everyone. Now, the company has refocused its priorities.
That means that you might be better off looking at a more tech-focused supplier. Newegg doesn’t publish shipping dates on its product pages, but Best Buy generally promises specific ship dates on its product pages, as it’s done for this USB-C hubRemove non-product link. In Best Buy’s case, the ship time is just a few days. (As another example, this Asus ROG Strix B450 motherboardRemove non-product link ships in three days, Asus said.) You can also pick up products from Best Buy stores, though it’s only offering “curbside” pickup for safety’s sake.
Amazon has traditionally offered exceptional convenience as a source for electronic goods as well as hand sanitizer. But for now, alternative stores might be the best source for your tech gear. Here’s hoping that they don’t follow suit and delay delivery times, too.
Different Function Of Linspace In Matlab With Examples
Introduction to Linspace MATLAB
MATLAB is a technical computing language. MATLAB gets its popularity from providing an easy environment for performing and integrating computing tasks, visualizing & programming.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
Uses of MATLAB include (but not limited to)
Computation
Simulation
Modeling
Data analytics (Analysing and Visualizing data)
Prototyping
Application development
Engineering & Scientific graphics
Linspace Function in MATLABIn this article, we will understand a very useful function of MATLAB called ‘linspace’. This function will generate a vector of values linearly spaced between two endpoints. It will need two inputs for the endpoints and an optional input to specify the number of points to include in the two endpoints.
X = linspace(a1, a2)
Now let us understand this one by one
1. X=linspace(a1,a2)This function will return a row of a vector of 100(default) linearly spaced points between a1 and a2
a1 and a2 can be real or complex
a2 can be either larger or smaller than a1
If a2 is smaller than a1 then the vector contains descending values
Here is an example to understand this:
Example #1X = linspace(-1, 1)
It will generate a vector of 100 evenly spaced vectors for the interval [-1, 1]
Output:
Example #2X = linspace(2, 3)
It will generate a vector of 100 evenly spaced vectors for the interval [2,3]
Output:
Example #3X = linspace(2, 1)
Here a2 is smaller than a1, it will generate a vector of 100 evenly spaced vectors for the interval [2,1] in descending order
Output:
2. X=linspace(a1,a2,n)This function will return a row of a vector of “n” points as specified in input for linearly spaced points between a1 and a2. This function gives control of the number of points and will always include the endpoints specified in the input as well.
If n is 1, the function will return a2 as output
If n is zero or negative, the function will return 1by0 empty matrix
Here is an example to understand this:
Example #1X = linspace(-1, 1, 7 )
It will generate a vector of 7 evenly spaced vectors for the interval [-1, 1]
Output:
Example #2X = linspace(2,3,5)
It will generate a vector of 5 evenly spaced vectors for the interval [2,3]
Output:
Example #3X = linspace(2, 3, 1)
Here n = 1, so the function will return a2 input parameter
Output:
Example #4Here n = 0, so function will return 1X0 empty double row vector
Output:
Vector of evenly spaced Complex numbersX = linspace(2+2i, 3+3i)
Here a1 and a2 are complex numbers, it will generate a vector of complex numbers for 100 evenly spaced points for the interval [2+21, 3+3i]
Output:
X= linspace(1+1i, 5+5i, 4)
It will generate a vector of complex numbers with 4 evenly spaced point for the interval [1+1i, 5+5i]
Output:
The linspace function in MATLAB provides us with an array/matrix comprising the desired number of values starting from and ending at a declared value. The produced array will have exactly the desired number of terms which will be evenly spaced. The values will be in the range of start and end values passed. So, the linspace function will help us in creating an instantiated matrix or array.
Recommended ArticlesThis is a guide to Linspace MATLAB. Here we discuss the introduction, Linspace Function in MATLAB and Vector of evenly spaced Complex numbers with examples and outputs. You can also go through our other suggested articles to learn more–
Python Range() Function: A Complete Guide (With Examples)
In Python, you can use the built-in range() function to generate a range of numbers from a start point to an end point.
For instance, let’s create a range of numbers from 0 to 5 and print them out:
numbers = range(0,6) for number in numbers: print(number)Output:
0 1 2 3 4 5Notice how the last number in the range() call is 6. This means the last number included in the range is actually 5.
In Python, you can call the range() function with one, two, or three parameters.
Here are some examples:
# Range from 0 to 9 range(10) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # Range from 5 to 9 range(5, 10) # 5, 6, 7, 8, 9 # Range from 1 to 100 with step size of 10 range(0, 110, 10) # 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 # Reversed range from 100 to 0 with step size of -10. range(100, -10, -10) # 100, 90, 80, 70, 60, 50, 40, 30, 20, 10If you’re looking for a short answer, I’m sure the above examples help you. But to truly learn how to use the range() function in different situations, I recommend reading the entire post.
This is a comprehensive guide to the range() function in Python. In this guide, you will learn thoroughly how to use the range() function in Python.
The range() Function in PythonIn Python, the built-in range() function produces an immutable sequence of numbers between start and end values.
The complete syntax of using range() function is as follows:
range(start, stop, step)Where:
start is the lower limit for the range. This is an optional parameter with a default value of 0.
stop is the upper limit for the range. The range consists of numbers until this value. Notice how it never includes the stop value in the range!
step is the step size for the range. This is an optional argument that defaults to 1. Each number in the range is generated by adding step to the previous value.
The range() function returns a range object. You can loop through this range object with a for loop. It is also possible to convert the range object into a list.
In Python 3, there are three syntactical variations of how to use the range() function:
range(stop)
range(start, stop)
range(start, stop, step)
Let’s go through each of these alternatives in more detail.
1. range(start)The most basic way to use the range() function in Python is by specifying only the end value for the range.
range(stop)When you do this, the range automatically starts from 0 and takes steps of size 1. It ends one before the stop value.
For example, let’s generate a range of numbers from 0 to 5:
numbers = range(6) for number in numbers: print(number)Output:
0 1 2 3 4 5Here the range starts from 0 because you did not specify a starting value. The range ends at the value of 5 instead of 6 due to the exclusive nature of range() function.
2. range(start, stop)Another way you can call the range() function in Python is by specifying both start and stop values. This is useful if you want the range to start from a value other than 0, which commonly is the case.
range(start, stop)For instance, let’s generate values from 5 to 10:
numbers = range(5,11) for number in numbers: print(number)Output:
5 6 7 8 9 10Notice that the start value 5 is included in the range, but the end value 11 is not. This might cause confusion if it’s your first time using the range() function.
3. range(start, stop, step)The third option to call the range() function is by specifying start, stop, and step parameters.
range(start, stop, step)The step parameter sets the interval for the range. In other words, it affects the way the range is generated by adding a value other than 1 to the previous number.
For example, let’s generate a range of values from 50 to 100 with by using 10 as a step size:
numbers = range(50,110,10) for number in numbers: print(number)Output:
50 60 70 80 90 100 The range() Function Return ValueNow that you know how to use the range() function in Python, let’s take a closer look at the return value.
In Python, the range() function returns a range object.
For example, let’s create a range of numbers and print the object. Let’s also print the type of the range using the built-in type() function:
numbers = range(5, 10) print(numbers) print(type(numbers))Output:
range(5, 10)The result of printing the range is not a list of numbers as you might expect. Instead, it’s a range object. In other words, the range() function returns a special range object.
The range object is iterable by nature. This means you can loop through it like any other iterable, such as a list. This is what you already saw in the previous examples.
Of course, you can also convert the range object into another iterable type, such as a list.
For example, let’s generate a range of numbers and convert it to a list with the built-in list() function:
numbers = range(50,110,10) numbers_list = list(numbers) print(numbers_list)Output:
[50, 60, 70, 80, 90, 100]Now the result is a regular Python list instead of a range object. So if you need to generate a range as a list, you can easily cast the range object into a list.
Keep in mind the range object is a range object for performance reasons. If there’s no need to cast the range to a list, don’t do it!
Reversed Range in PythonIn Python, it is possible to create a reversed range by specifying a negative step size to the range() function call.
For example, let’s generate a range of numbers from 100 to 50:
numbers = range(100, 40, -10) for number in numbers: print(number)Output:
100 90 80 70 60 50Make sure you understand why this works.
The range starts from the start parameter, but it stops one step before the stop parameter. Thus the stop is set to 40 to include 50 in the range.
As the step is -10, the range takes steps of size -10. In other words, it decreases the start by 10 until the stop value.
But why do you need to specify the step value at all? How about range(100, 40)?
As you remember, the range(100, 40) would mean that the step is 1 (by default) which would mean range(100, 40, 1).
This confuses Python as it tries to get from 100 to 40 by adding ones to 100, which is impossible.
Thus the result is an empty range.
numbers = range(100, 40) numbers_list = list(numbers) print(numbers_list)Output:
[] Negative Range in PythonIn Python, you can use the built-in range() function to produce a range of negative numbers.
When speaking about negative ranges in Python, you may refer to:
Negative range with increasing numbers, that is, a positive step.
Negative range with decreasing numbers, that is, a negative step.
Let’s see an example of each.
Negative Range with Increasing NumbersFor example, let’s create a range of numbers from -1 to -5:
numbers = range(-1, -6, -1) for number in numbers: print(number)Output:
-1 -2 -3 -4 -5Notice how you need a negative step size to make the range work. This is because it is not possible to get smaller values by adding positive values.
In other words, if you did not specify a negative step:
numbers = range(-1, -6) print(list(numbers))Your result would be an empty range, that is, no values at all:
[] Negative Range with Increasing NumbersTo produce a range of negative values in increasing order, use the built-in range() function the same as you use it with positive numbers.
For example, let’s create a range of negative numbers from -10 to -5.
numbers = range(-10, -4) for number in numbers: print(number)Output:
-10 -9 -8 -7 -6 -5Notice how the step parameter is not needed as you are increasing the numbers by one.
Range Indexing in PythonIn Python, the range() function produces a range object. This range object supports indexing the same way other iterables, such as lists, do.
For example, let’s get the second number in a range of numbers:
numbers = range(1, 6) # 1, 2, 3, 4, 5 second = numbers[1] print(second)Output:
2Needless to mention range objects support negative indexing too.
For example, let’s get the last element of a range using negative indexing -1:
numbers = range(1, 6) # 1, 2, 3, 4, 5 last = numbers[-1] print(last)Output:
5 Range Slicing in PythonPython range objects support slicing. This means you can get a partial group of numbers from a range using slicing.
When you slice a range object in Python, you get a range object as a result. This range object contains the part of the original range.
If you are unfamiliar with slicing in Python, feel free to check this article.
For example, let’s get the first 3 numbers in a range:
numbers = range(1, 10) first_three = numbers[0:3] for number in first_three: print(number)Output:
range(1, 4)A common way to use slicing in Python is to reverse an iterable with slicing by [::-1]. You can do the same for a range of numbers too.
For instance, let’s reverse a range of numbers from 1 to 5:
numbers = range(1, 6) rev = numbers[::-1] for number in rev: print(number)Output:
5 4 3 2 1 Inclusive RangeThe Python range() function produces a range of values that does not include the last value by default.
For example range(0,5) produces a range of values 0, 1, 2, 3, 4.
To create an inclusive range, that is, to add the stop value into the range too, add the step value to the stop value.
For example, let’s create a range of values from 1 to 5 inclusively:
step = 1 numbers = range(1, 5 + step, step) print(list(numbers))Output:
[1, 2, 3, 4, 5] For Loops with range() in PythonA common way to utilize the range() function is with for loops.
Loop Through Numbers with range()The most basic use case is when looping through numbers from n to m.
For example, let’s print numbers from 1 to 5:
numbers = range(1,6) for number in numbers: print(number)Output:
1 2 3 4 5 Loop with an Index Using range() FunctionAnother common use case for the range() is to access the index (or indexes) of an element with a for loop.
For example, let’s print a list of names and their index in the list:
queue = ["Alice", "Bob", "Charlie", "David"] for pos in range(len(queue)): print(f"{pos}: {queue[pos]}")Output:
0: Alice 1: Bob 2: Charlie 3: DavidAlthough there’s a much better solution to get the indexes by using the enumerate() function. Let’s have a look at how this function works.
Alternative to range() Function with For LoopsNow you know the range() can be used in a for loop to get the index of the elements. Meanwhile, this is commonly taught for beginners, it is not the ideal way to do it.
Instead, you should use a built-in enumerate() function.
For example, let’s repeat the example of printing the list of names and their index. Let’s not use range() this time, but enumerate() instead:
queue = ["Alice", "Bob", "Charlie", "David"] for pos, name in enumerate(queue): print(f"{pos}: {name}")Output:
0: Alice 1: Bob 2: Charlie 3: DavidIn short, the enumerate() function couples the list elements with their index.
In the above example, the enumerate(queue) produces an object with position, name pairs:
[(0, 'Alice'), (1, 'Bob'), (2, 'Charlie'), (3, 'David')] ConclusionToday you learned how to use the range() function in Python.
To recap, the range() function returns a range of values from n until m.
For example range(5) returns numbers 0,1,2,3,4.
The result of the range() function is a range object. You can use the range object to loop through the range. Alternatively, you can cast the range object to a list to get a list that represents a range of numbers.
There are three ways to call the range function in Python:
range(start)
range(start, stop)
range(start, stop, step)
Thanks for reading. Happy coding!
Further Reading50 Python Interview Questions
Update the detailed information about Using Lambda Function With Amazon S3 on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!