In Python, can use use the
range() function to get a sequence of indices to loop through an iterable. You'll often use
range() in conjunction with a
In this tutorial, you'll learn about the different ways in which you can use the
range() function – with explicit start and stop indices, custom step size, and negative step size.
Let's get started.
Before looking at the different ways of using the
range() function, you've got to understand how it works.
range()function returns a range object.
This range object in turn returns the successive items in the sequence when you iterate over it.
As stated above, the range function does not return a list of indices. Rather, it returns a range object which returns the indices as and when you need them. This makes it memory-efficient as well.
You can use the
range() function with the following general syntax:
When you use this syntax in conjunction with a loop, you can get a sequence of indices from
start up to but not including
stop , in steps of
stop, which can be any positive integer. If you specify a floating point number instead, you'll run into a
my_range = range(2.5)
startindex, the default start index of
stepvalue, the default step size of
In the subsequent sections, you'll learn about the different ways of using the
range()Function to Loop Through Any Iterable
As mentioned in the previous section, you only need one positive integer to use the
range() function. The syntax is shown below:
You can use the above line of code to get a sequence from
▶ Consider the following example where you call
range() with 5 as the argument. And you loop through the returned range object using a
for loop to get the indices 0,1,2,3,4 as expected.
for index in range(5): print(index) #Output 0 1 2 3 4
If you remember, all iterables in Python follow zero-indexing. This is why it's convenient to use
range() to loop through iterables.
An iterable of length
len-1 as the valid indices. So to traverse any iterable, all you need to do is to set the
stop value to be equal to
len. The sequence you'll get –
len-1 – is the sequence of valid indices.
▶ Let's take a more helpful example. You have a list
my_list. You can access all items in the list by knowing their indices, and you can get those indices using
range() as shown below:
Remember, you can use Python's built-in function
len to get the length of any iterable. In the above code, you use both the valid indices, and the list items at those valid indices. Here's the output:
my_list is 7 items long, and the indices obtained are from 0 through 6, as expected.
Sometimes, you may need to use negative integers instead. In this case, if you use only the
stop argument, you'll not get the desired output, though the code doesn't throw an error.
This is because the default
start value is assumed to be
0, and you cannot count up from
for index in range(-5): print (index) #Output #NOTHING HERE
range()Function with Explicit Start and End Indices
You may not always want to start at zero. You can start at any arbitrary index by setting the
start value to the index that you'd like to start from. The syntax is as follows:
In this case, you'll be able to get the sequence:
start + 1,
start + 2, and so on up to
▶ In the example below, you're starting at 10, count all the way up to but not including 15 in steps of 1.
for index in range(10,15): print(index) #Output 10 11 12 13 14
In the previous section, you saw how using only the
stop argument won't work when you need negative integers. However, when you specify
stop indices explicitly, you can as well work with negative integers.
▶ In this example, you're trying to count up from -5 in steps of 1. Always keep in mind that the counting stops at the value that's one less than the
for index in range(-5,0): print(index) #Output -5 -4 -3 -2 -1
range()Function with a Custom Step Size
Instead of traversing an iterable sequentially, you may sometimes want to stride through it, accessing every
k-th element. This is when the optional
step argument comes in handy. The general syntax is shown below:
When you use this syntax and loop through the range object, you can go from
stop-1 with strides of size
start + step,
start + 2*step, and so on up to
start + k*stepsuch that
start + k*step<
start + (k+1)*step>
▶ In the example below, you'd like to go from 0 to 20 in steps of 2. Notice how the last index printed out is 19. This is because, if you take another step, you'll be at 21 which is greater than 20.
Always remember, the last value you get can be as close to
stop as possible, but can never be
for index in range(1,20,2): print(index) #Output 1 3 5 7 9 11 13 15 17 19
range()Function with a Negative Step Size
So far, you've learned to use the
range() function with
stop indices, and a specific step size, all the while counting up from
If you need to count down from an integer, you can specify a negative value for
step. The general syntax is:
startin steps of
negative_step, up to but not including
start - negative_step,
start - 2*negative_step, and so on up to
start - k*negative_stepsuch that
start - k*negative_step>
start - (k+1)*negative_step<
negative_step = -1to count down covering each number.
▶ In this example, you'd like to count down from 20 in steps of -2. So the sequence is 20, 18, 16, all the way down to 2. If you go another 2 steps lower, you'll hit 0, which you cannot as its smaller than the stop value of 1.
for index in range(20,1,-2): print(index) #Output 20 18 16 14 12 10 8 6 4 2
It's easy to see that
stop to be able to count down.
for index in range(10,20,-1): print(index) #Ouput #Nothing is printed - the sequence is empty.
▶ In the above example, you try counting down from 10 to 20 which is impossible. And you don't get any output which is expected.
reversed()Functions to Reverse a Sequence
If you need to access the elements of an iterable in the reverse order, you can use the
range() function coupled with the
reversed()function returns a reverse iterator over the values of a given sequence.
▶ Let's take our very first example, where we used
range(5). In the example below, we call
reversed() on the range object. And we see that we've counted down from 4 to 0.
for index in reversed(range(5)): print (index) #Output 4 3 2 1 0
As you can see, this is equivalent to using
range(4,-1,-1). If you prefer, you may use the
reversed() function instead of
negative_step argument discussed in the previous section.
In this tutorial, you've learned the different ways in which you can use the
range() function. You can try a few examples to get a different sequence each time. This practice will help you use
range() effectively when looping through iterables.
Original article source at https://www.freecodecamp.org
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.
#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
The_ range__ type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops._
The value of the start parameter (or
0 if the parameter was not supplied)
The value of the stop parameter
The value of the step parameter (or
1 if the parameter was not supplied).
If the step is 0, it will raise ValueError.
The arguments to the range function should be integers. (either built-in
int or any object that implements the
__index__ special method)
Example 1:Only the stop parameter is given.
stopis given as 10.
r=range(10) print (r)#Output:range(0, 10) print (type(r))#Output:<class 'range'> print (list(r)) #Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2:Only the start and stop parameter is given.
r=range(1,10) print (r)#Output:range(1, 10) #Converting range object to list print (list(r)) #Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 3:start, stop and step parameter is given
r=range(1,10,2) print (r)#Output:range(1, 10, 2) #Converting range object to list print (list(r)) #Output:[1, 3, 5, 7, 9]
Example 4:We can also decrement step by mentioning a negative number.
#python-range #python-programming #python #python3 #software-development #function
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu" >>> LastName = "Jordan" >>> FirstName, LastName = LastName, FirstName >>> print(FirstName, LastName) ('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development