Python range() Function Explained with Examples

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 for loop.

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.

Understanding Python's range() Function

Before looking at the different ways of using the range() function, you've got to understand how it works.

The 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:

range(start,stop,step)

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 step.

  • You must specify the required argument stop, which can be any positive integer. If you specify a floating point number instead, you'll run into a TypeError as shown:
my_range = range(2.5)

  • If you don't specify the start index, the default start index of 0 is used.
  • If you don't specify the step value, the default step size of 1 is used.

In the subsequent sections, you'll learn about the different ways of using the range() function.

How to Use Python's 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:

range(stop)

You can use the above line of code to get a sequence from 0 through stop-1 : 0, 1, 2, 3,..., stop-1.  

▶ 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 has 0, 1, 2, ..., 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 – 0, 1, 2, ..., 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:

my_list = ["Python","C","C++","JavaScript","Julia","Rust","Go"]
for index in range(len(my_list)):
  print(f"At index {index}, we have {my_list[index]}")

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:

Notice how 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 0 to -5.

for index in range(-5):
  print (index)
  
  
#Output
#NOTHING HERE

How to Use Python's 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:

range(start,stop)

In this case, you'll be able to get the sequence: start, start + 1, start + 2, and so on up to stop-1.

▶ 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 start and 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 stop index.

for index in range(-5,0):
  print(index)
  
#Output
-5
-4
-3
-2
-1

How to Use Python's 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:

range(start,stop,step)

When you use this syntax and loop through the range object, you can go from start to stop-1 with strides of size step.

  • You'll get the sequence: start, start + step, start + 2*step, and so on up to start + k*step such that  start + k*step < stop and start + (k+1)*step > stop.

▶ 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 stop.

for index in range(1,20,2):
  print(index)

#Output
1
3
5
7
9
11
13
15
17
19

How to Use Python's range() Function with a Negative Step Size

So far, you've learned to use the range() function with start and stop indices, and a specific step size, all the while counting up from start to stop.

If you need to count down from an integer, you can specify a negative value for step. The general syntax is:

range(start,stop,<negative_step>)
  • The range object can now be used to return a sequence that counts down from start in steps of negative_step, up to but not including stop.
  • The sequence returned is start, start - negative_step, start - 2*negative_step, and so on up to start - k*negative_step such that start - k*negative_step > stop and start - (k+1)*negative_step < stop.
  • There's no default value for negative step – you must set negative_step = -1 to 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 start > 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.

How to Use Python's range() and 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.

Python's built-in 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.

Conclusion

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

#python

What is GEEK

Buddha Community

Python range() Function Explained with Examples
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

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

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

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

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

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#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

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

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

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

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

5 Reasons to Utilize Python for Programming Web Apps 

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

Robust frameworks 

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

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

Simple to read and compose 

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

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

Utilized by the best 

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

Massive community support 

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

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

Progressive applications 

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

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

Summary

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

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

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

An Introduction to the Python Range Function.

Range:

The_ range__ type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops._

range(stop)
range(start,stop,step)

**start**

The value of the start parameter (or 0 if the parameter was not supplied)

**stop**

The value of the stop parameter

**step**

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.

range(10)

  • start by default will be 0 and **step **by default will be 1
  • stop is given as 10.
  • stop value is excluded. It generates value until 9 only.
  • It will return a range object containing numbers starting from 0 to 9.
  • We can convert the range object to list using list() constructor.
  • We can also iterate using for loop
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.

**range(1,10)**

  • step by default will be 1
  • It will generate a sequence of numbers starting from 1 to 9.
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

range(1,10,2)

  • It will generate a sequence from** 1**, increment by 2, and will stop at 9.
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.

range(10,1,-2)

  • It will generate a sequence of numbers from 10, decrement by 2, and stop at 1.
  • Iterating through range object using for loop.

#python-range #python-programming #python #python3 #software-development #function

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

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.

Let’s get started

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