Consider a list of integers: a= range(5) a out: 0,1,2,3,4 It has indices from 0,1,2,3,4. For example: If you try: a0, a1, a4, a-2 OUT: 0 1 4 3 When you try to access the index of the list of ‘a’ which is not from the above i. The fix to this I think is for zero byte packets and the same issue is also in SocketIo in ufora/ufora#203 and is to add at line 142 of transports.py, two lines and an indent.
In this article we will discuss how to access characters in string by index.
Accessing characters by index in string | indexof
In Python indexing of strings starts from 0 till n-1, where n is the size of string. So characters in string of size n, can be accessed from 0 to n-1.
Suppose we have a string i.e.
Let’s access character at 5th index i.e.
We can access and use the character i.e.
2 | print('Character at index 5 is : ',sampleStr[5]) |
Accessing string elements by negative index
We can also access the character in string using negative indexing i.e.
- string[-1] will return the last character of string
- string[-2] returns the second last character of string
- If string size is n then string[-n] will return the first character of string
For Example :
2 4 | print('Last character in string : ',sampleStr[-1]) print('Second Last character in string : ',sampleStr[-2]) print('First character in string : ',sampleStr[-len(sampleStr)]) |
Output:
2 4 6 | Modifying character in string by Index As strings are immutable so we can modify the contents of string in python sampleStr[5]='s' |
It will throw error like this,
TypeError:'str'object does not support item assignment |
Accessing Out Of range character in python string
Accessing element in string that is out of its range i.e. greater than its length, will throw IndexError exception. Therefore we should always check the size before accessing element by index i.e.
2 4 6 | try: exceptIndexError: |
or we can can catch the exception too i.e.
2 4 6 8 | # Check the size of string before accessing character by index ifn<len(sampleStr): else: |
What we can do by accessing characters from string by index ?
- We can loop over the string contents in forward and reverse direction
- We can slice strings to get sub strings.
We will discuss this in next articles.
Complete example is as follows,
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 | Accessing character in string by Index # Access character at index 5 Accessing character in string by Negative Index print('Last character in string : ',sampleStr[-1]) print('Second Last character in string : ',sampleStr[-2]) print('First character in string : ',sampleStr[-len(sampleStr)]) '' As strings are immutable so we can modify the contents of string in python #sampleStr[5] = 's' '' Accessing Out of range elements in string will cause IndexError try: exceptIndexError: # Check the size of string before accessing character by index ifn<len(sampleStr): else: main() |
Output:
Example Two – using two arguments (i.e., start and stop) in range() function
Output:
- Only two arguments (the start and stop) are passed to the range function.
- So by default, it took step argument value as 1.
Example Three – using all three arguments in range() function
Output:
All three arguments are specified. i.e.
start = 1
, stop = 10
, step = 2
. Note:- In the above program step value is 2 so the difference between each number is 2.Points to remember about python range() function arguments
- range() function only works with the integers i.e., whole numbers.
- All argument must be integers. You can not pass a string or float number or any other type in a start, stop and step argument of a range().
- All three arguments can be positive or negative.
- The step value must not be zero. If a step is zero python raises a ValueError exception.
Python range() with for loop
As you know for loop executes a block of code or statement repeatedly for the fixed number of times. Using for loop we can iterate over a sequence of numbers produced by the
range()
function.Let see this with an example. Suppose we have a list of 5 numbers and you want to display each element by doubling it let see how to do it using a for loop and range() function.
Output:
- Here using a
len(list)
, we got total elements of a list so we can iterate for loop fixed number of time. In each iteration using a range() function loop gets the index of the current element. - Note: variable
i
is not getting the value 0, 1, 2, 3, 4 at the same time.i
get value sequentially. i.e., in the first iterationi= 0
. in the second iterationi
become 1 and so on.
I have created a program using for loop and range() function to print various numeric patterns to understand the use of for loop and range function.
Python range inclusive
The
range(n)
is of exclusive nature that is why it doesn’t include the last number in the output. i.e., The given end point is never part of the generated result.For example,
range(0, 5) = [0,1,2,3,4]
. I.e. it generates integers from 0 to up to 5 but doesn’t include 5. If you want to include the last number in the output i.e., If you want an inclusive range then pass stop
argument value as stop+step
.Inclusive range() example in Python.
Output:
Example 2: Inclusive range
Output:
Python range Step
A step is an optional argument in the range function. The step is a difference between each number in the sequence. The default size of a step is 1 if not specified. If the step size is 2, then the difference between each number is 2.
We can perform lots of operations by effectively using step argument such as reversing a sequence, printing negative ranges.
Decrementing with range using negative step
We can use negative values in all the arguments of range() function i.e., start, stop and step. Let us see how.
Output:
![Index Index](/uploads/1/2/4/8/124897764/782616711.jpg)
Let’s understand above program:
we set,
start = -2
stop = -10
, step = -2
.Decrementing with the range from Negative to Positive number
Here in this example, we can learn how to use step argument to display a range of numbers from negative to positive.
The output of the above program
Python range from Positive to Negative number
Here in this example, we can learn how to use step argument effectively to display numbers from positive to negative.
Output:
Convert Python range() to List
Python 3’s range uses the generator. Python 3’s range() will produce value when for loop iteration asked for it. i.e., it The
range()
doesn’t produce all numbers at once.Python range() function returns an immutable sequence object of integers, so its possible to convert range() output to python list. Use list class to convert range output to list. Let’s understand this with the following example.
Output:
Using float Numbers in Python range()
Python range() function doesn’t support the float numbers. i.e., we cannot use floating-point or non-integer number in any of its argument. we can use only integer numbers.
However, we can create a custom range function where we can use float numbers like 0.1 or 1.6 in any of its argument. I have demonstrated this in the below example.
Output:
Also, see other ways to use float numbers in range() function.
Reverse range in python
If you want to print sequence of numbers within range by descending order or reverse order then its possible, there are two ways to do this.
First is to use a negative or down step value. i.e., set the third argument of a
range()
to -1
.For example, if you want to display a number sequence like [5,4,3,2,1]. Use negative step value. The following code shows the same.
Output:
Alternatively, use the reversed function.
The
reversed
function used to reverse a list of any type. To use the reversed
function you need to convert a range output to list first. Let see this with an example.Output:
Python’s range() vs xrange() Functions
range() function works differently between Python 3 and Python 2.
The difference between range() and xrange() functions becomes relevant only when you are using python 2. Because in Python 3 xrange() is renamed to range() and original range() function was deprecated.
Working of range and xrange in Python 2
- Both the range() and xrange() function generates the sequence of numbers. but
range()
produce a list, andxrange()
produces an xrange object i.e. a sequence object of type xrange. - range() generates all numbers at once.
- xrange() doesn’t generate all numbers at once. it produces number one by one as for loop moves to the next number
We can test the type of these functions In Python 2 with the following examples: –
Do you know why they deprecated original python2’s range() function in Python 3? The main reason behind deprecation of the original range() function is memory and speed. Please take a look at range() vs xrange() and their use for more in detail information
Should we always favor range() over xrange()?
If you are using python 2.x then yes. as you know in python 2.x range() function loads all the numbers in the main memory before iterating them by for loop this leads to high memory usage and increased execution speed.
If you want to write code that will run on both Python 2 and Python 3, you should use range().
Python range() over character or alphabet
Is there a way print range of characters or alphabets? For example like this.
Note: Above code is a pseudo-code.
Yes, It’s possible using the custom generator. let’s see the example. in the following example, I have demonstrated how to generate ‘a’ to ‘z’ alphabet using the custom range() function. this is inclusive, means it also includes the last character.
Here we used a ASCII value range and then convert an ASCII value to a letter using a
Here we used a ASCII value range and then convert an ASCII value to a letter using a
Chr()
function.Python Program to Generate letters from ‘a’ to ‘z’ using custom range() function
How does the Python range() function work?
Python range() return value is determined by formula and some value constraints.
Note: If a step is a non-zero, Python range() function checks the value constraint. range() returns an Empty sequence If it doesn’t meet the value constraint.
So you must be thinking why does python range(start, end) not include end ? it has a very simple answer because index always starts with ZERO in python. if you count total numbers between range (5) you will get [0,1,2,3,4] i.e. total count is 5.
Concatenating the result of two range() function in python
Let say you want to add
range(5) + range(10,15)
. (Note: this code is a pseudo-code.) And you want the concatenated range like [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
.Can we concatenate the output of two range functions?
Yes, this is possible using itertools. using chain() function of itertools we can do this.
Program: Concatenating two range function results.
Output:
Access Python range() result with its index value
range() is constructor returns a range object which is nothing but a sequence of numbers, this range object can also be accessed by its index using slice notation. It supports both positive and negative indices. below example explains the same.
Output:
you can also convert python range() output to list and access this list with its index like this.
Output:
Next Steps
To practice what you learned in this article, I have created a Python Basic Quiz and Exercise.
- Solve our Python essential exercise for beginners to have a better understanding of Python basic concepts.
- Solve our Basic Python Quiz for beginners to test your fundamental Python skills.
Let me know your comments and feedback in the section below.