Python Range Function: Built-In Functions
Python Range Function: Built-In Functions
Python range() Function
❮ Built-in Functions
Example
Create a sequence of numbers from 0 to 5, and print each item in the sequence:
x = range(6)
for n in x:
print(n)
Try it Yourself »
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax
Parameter Values
Parameter Description
stop Required. An integer number specifying at which position to stop (not included).
More Examples
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Example
x = range(3, 20, 2)
for n in x:
print(n)
LO MISMO:
print(i)
SALIDA:
11
13
15
17
19
11
13
15
17
19
BITWISE OPERATORS
The Operators:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are
zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x&y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1,
otherwise it's 0.
x|y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0,
otherwise it's 1.
~x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for
a 1. This is the same as -x - 1.
x^y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x
if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall
off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let
the rightmost bits fall off
Python Lists
❮ PreviousNext ❯
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Try it Yourself »
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
lst = [1,2,3,4]
print(lst[-3:-3])
OUTPUT []
Example
This example returns the items from the beginning to "orange":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
print(thislist[-4:-1])
Python Tuples
❮ PreviousNext ❯
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Try it Yourself »
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Try it Yourself »
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Try it Yourself »
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new tuple with the specified
items.
Example
Return the third, fourth, and fifth item:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Try it Yourself »
Note: The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Try it Yourself »
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Try it Yourself »
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Try it Yourself »
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Try it Yourself »
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Try it Yourself »
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Try it Yourself »
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.
Example
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Try it Yourself »
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer
exists
Try it Yourself »
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
Example
Using the tuple() method to make a tuple:
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
Python Strings
❮ PreviousNext ❯
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.
Example
print("Hello")
print('Hello')
Try it Yourself »
Example
a = "Hello"
print(a)
Try it Yourself »
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Try it Yourself »
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Try it Yourself »
Note: in the result, the line breaks are inserted at the same position as in the
code.
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Try it Yourself »
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Try it Yourself »
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters from position 5 to position 1 (not included), starting the
count from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
Try it Yourself »
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Try it Yourself »
String Methods
Python has a set of built-in methods that you can use on strings.
Example
The strip() method removes any whitespace from the beginning or the end:
Try it Yourself »
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Try it Yourself »
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Try it Yourself »
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Try it Yourself »
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Try it Yourself »
Check String
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.
Example
Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
Try it Yourself »
Example
Check if the phrase "ain" is NOT present in the following text:
Try it Yourself »
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
Try it Yourself »
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Try it Yourself »
String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
Try it Yourself »
Example
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Try it Yourself »
The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Try it Yourself »
You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Try it Yourself »
Escape Character
To insert characters that are illegal in a string, use an escape character.
Example
You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
Try it Yourself »
Example
The escape character allows you to use double quotes when you normally would
not be allowed:
Try it Yourself »
Other escape characters used in Python:
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
Note: All string methods returns new values. They do not change the original
string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where
format() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of wh
rindex() Searches the string for a specified value and returns the last position of wh
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Python File Write
❮ PreviousNext ❯
Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Run Example »
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Run Example »
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
❮ PreviousNext ❯
Python ord() and chr() are built-in functions. They are used to convert a
character to an int and vice versa.
Python ord() and chr() functions are exactly opposite of each other.
PYC File Format
Conway’s law is an observation that the design of any system is significantly affected by the
communications structure of the organization that develops it.
Python Lambda
❮ PreviousNext ❯
Syntax
lambda arguments : expression
Example
A lambda function that adds 10 to the number passed in as an argument, and
print the result:
x = lambda a : a + 10
print(x(5))
Try it Yourself »
Example
A lambda function that multiplies argument a with argument b and print the
result:
x = lambda a, b : a * b
print(x(5, 6))
Try it Yourself »
Example
A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Try it Yourself »
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number
you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Try it Yourself »
Or, use the same function definition to make a function that always triples the
number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Try it Yourself »
Or, use the same function definition to make both functions, in the same
program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Try it Yourself »