Python
Lists in Python | Complete Guide to Python Lists with Examples
In this 5th lesson, we are going to look at an important topic in Python, which is lists. Lists in Python are used to handle a large amount of data. Remember how we talked about variables in Python in a previous lesson? Well, a list is used to store multiple elements in a single variable. Hence, a list is a collection of data that allows duplicate data as well. These data can be in the form of any data type. We can do a lot using lists in Python, and also, there are many functions related to lists.
First of all, let’s look at how to create a list.
flowers = [] #empty list fruits = ["Banana","Apple","Grape","Mango"] #a list of string values random_list = ["Hi","my",267,7.9] #a list containing elements of multiple data types
You can print these lists as shown below.
print(random_list)
The output:

You can access the elements in the list using the index. Remember that the indexes start with zero.
print(fruits[0]) #prints first element print(fruits[-1]) #prints last element print(fruits[1:]) #prints all the elements starting from the second element print(fruits[1:3]) #prints index 1 & 2 elements but not 3
The output:

You can assign a new value to an element, as shown in the below code.
fruits[0] = "Pineapple" print(fruits)
The output:

Now that you have basic knowledge of lists, let’s dig into some functions you can use with lists in Python.
List Functions in Python
There are so many different functions that you can use with lists. These functions make it easier to work with lists, and you are given the ability to do a lot of things without worrying about writing a lot of codes. Here we will be looking at some of the most used list functions in Python.
Initially, let’s create two lists to work with.
vehicles = ["car","van","bus","lorry","bicycle"] countries = ["England","Russia","China","India","Australia"]
The below code shows you how to use functions and manage the two lists we created.
vehicles.extend(countries) #adds two lists together
print(vehicles)
countries.append("Brazil") #adds a new element at the end of the countries list
print(countries)
countries.insert(1,"Poland") #new element added at index 1
print(countries)
countries.remove("India") #element removed
print(countries)
vehicles.clear() #remove all items from list
print(vehicles)
countries.pop() #remove last elemet
print(countries)
print(countries.index("Australia")) #index of the given element gets printed
print(countries.count("India")) #count of an element
print(countries.sort()) #sort in ascending(alphabetical) order
vehicles = countries.copy() #elements of countries are copied to vehicles list
print(vehicles)
print(len(vehicles)) #give length of a list
The output:

Please go through all the functions and pay attention to what they do. Try on your own and see if you get the same results.
There’s an alternative way of creating a list using list() function is given below.
mylist = list(("guava", "banana", "cherry")) # note the double round-brackets
print(mylist)
The output:

The lists we talked about so far are one-dimensional. Python provides the option to make 2D lists as well. They can have any number of rows and columns. Look at the below code and understand how a 2D list is created.
number_grid = [ [1,2,3], [4,5,6], [7,8,9] ] print(number_grid) print(number_grid[1][2]) #access an element through row and column indexes
The output:

In the upcoming lessons, we will talk about how to use for loops to go through lists in Python. As we said in the beginning, a list is a collection of data. There are few other ways to represent a collection of data in Python.
- Tuple – Ordered and unchangeable. Duplicate elements are allowed.
- Set – Unordered and unindexed. Duplicate elements are not allowed.
- Dictionary -Unordered and changeable. Duplicate elements are not allowed.
These collection types have some differences in syntaxes and functionalities. Selecting the suitable type for a particular data set, increases efficiency and security. Therefore you have to learn their differences and use them accordingly.
Let’s do a small coding example using lists in Python. In this example, a for-loop is used. More details on for loops will be given in later lessons. For now, understand that using a for-loop, you can go through all the elements in a list. Let’s get the sum of all the elements in a list. Look at the given code.
number_list = [1,6,43,-8,4.7,10,-100]
sum = 0
#for-loop
for number in number_list:
sum = sum + number
#print answer
print(sum)
The output will be -43.3
Please go through this article to get more information about Lists in Python.
I hope you got a good understanding of lists in Python. Practice the examples we talked about and get familiar with list functions as well. This lesson will be beneficial when you start writing your programs. Keep practicing until the next lesson!
Python
File Handling in Python | Complete Guide to File Handling
Python supports file handling and allows several functionalities with files. The implementation of file handling in other languages is a bit complicated, whereas file handling in Python is very easy and simple. Each line of a file is terminated with a special character, called the EOL (End of Line characters), so that the interpreter knows that a new line has begun. To work with a file, the first step is to open the file.
Use of open() Function
We use open () function to open a file in Python. Two arguments, that accept file name and the mode in which the file should be opened, must be passed when calling the open function. Once the open function is called passing the correct arguments, it will return a file object. Files can be opened in four modes. For each mode, the following characters are assigned to pass as the arguments.
- “ r “– read mode
- “ w “– write mode
- “ a “– append mode
- “ r+ “- read and write mode
If no argument is passed as the mode, Python will consider it “ r ” by default. Note that, if you open a file in reading or append mode, the file name you entered must already exist. On the other hand, opening a file in write mode doesn’t require that condition. If you open a file in the write mode, with a file name that doesn’t exist, the program will create a new file by that name.
Read Mode in Python File Handling
Let’s see what we can do with the read mode. First, create a text file and name it as myFile.txt. Then, type anything you want in that file and save it. Note that the output will differ according to what you’ve typed inside your .txt file. The code is given below consists of many read functions to output the data inside the file. Observe them and understand the functionalities of them.
Let’s open the file.
# open a file
my_file = open("test.txt","r")
Now try these read methods and check outputs.
print(my_file.readable()) # return True if file is readable
The output:

print(my_file.read()) # print entire file
The output:

print(my_file.readline()) # print first line
The output:

print(my_file.readlines()) # lines put into an array and printed
The output:

for i in my_file:
print(i)
The output:

Write Mode in Python File Handling
The write mode is used to write something to a file. If you choose to write in a file that already has some context, the file will be overwritten. Let’s use the write function on the same text file we used before.
# open a file in write mode
my_file = open("test.txt","w")
# write
my_file.write("The file has new data.")
# close file
my_file.close()
If you go back to your test.txt file, you can see that the new content has overwritten the file. The close() method terminates all the resources in use, and it is good to close the file once you’ve finished working with it.
Append Mode in Python File Handling
Append mode is used when we want to add new content to the file. This doesn’t overwrite the file. It only appends new data.
# open a file in append mode
my_file = open("test.txt","a")
# write
my_file.write(" This is the append mode.")
# close file
my_file.close()
Once the code is executed, you can go back and see how the new content is added at the end of the file. These are the basics of file handling in Python. To dig a little deeper, you can look into many other functions associated with file handling in Python. One such function is the split() function. Below code spits each line into words separated by spaces.
# Use of split() function
my_file = open("test.txt","r")
data = my_file.readlines()
for line in data:
words = line.split()
print (words)
The output:

Now that you have an understanding of file handling in Python, go on and try different tasks improving the examples you studied here. Keep practicing until the next lesson!
Python
Functions in Python | Better Insight into Functions
When you’re working on a python program, you may find tasks that need to be done multiple times. It’s not a good practice to write the same block of code over and over again whenever you need that specific task to be done. As a solution to this situation, we use functions in python. The block of code for the task you need can be put inside a function. Whenever you call the function, you can get the expected result.
How to create functions in Python
To create a function, the keyword “def” is used along with the function name. Give any descriptive name as the function name, and whenever you want to call the function, that name should be used. Let’s create a function to print something.
# create a function
def print_something():
print("This is a function")
Note that, when you run the above code, nothing gets printed on the terminal. The reason is that we’ve only created the function. To execute the function, we need to call it. Make sure to create a function before you call it.
How to call functions in Python
# create a function
def print_something():
print("This is a function")
# call the function
print_something()
The output:

Arguments in Python
Sometimes we need to pass values to the function. This is needed when the code inside the function requires some value to work with. These values are called arguments. Inside the brackets after the function name, any number of arguments can be passed into the function, separated by a comma. The above example didn’t require any arguments. In the below example, first, we ask the user to input his name and age. Then, we create a function to output a description of the user.
# get user inputs
name = input("Enter your name: ")
age = input("Enter your age: ")
# create function
def user_description(username,userage):
print(f"Hi, your name is {username} and you are {userage} years old.") # formatted string
# call the function
user_description(name,age)
The output:

Note that we’ve entered the name as “Mike” and the age as 25. When calling the function, the correct number and sequence of arguments should be used to get the expected results. Or else you can pass the arguments in the key = value form. In that method, the order of the arguments does not matter. Look at the below code on passing the arguments with key = value syntax.
user_description(userage=age,username=name)
Python gives us an option to use default values as arguments too. If no arguments are passed, the default values would be used.
# get user inputs
name = input("Enter your name: ")
age = input("Enter your age: ")
# create function
def user_description(username = "Jane",userage="20"):
print(f"Hi, your name is {username} and you are {userage} years old.") # formatted string
# call the function
#user_description(name,age)
user_description()
The output:

As shown in the above example, since we haven’t passed arguments when calling the function, the default arguments are used. Therefore, even though we entered the name and the age as Tom and 28, respectively, those values are not printed.
Passing a List as an Argument in Python
You can pass any value belonging to any data type as an argument. The below example shows a situation where a list is passed as an argument.
# create function
def my_function(my_list):
for x in my_list:
print(x)
fruits = ["orange", "banana", "berry"]
# call the function
my_function(fruits)
The output:

Return Values from a Function in Python
By using the return statement, you can return a value from a function. In the below example, first, the program asks for two numbers from the user. Then a function is created to return the sum of the two numbers. After calling the function, a message is printed for the user.
# get user inputs
number1 = input("Enter number1: ")
number2 = input("Enter number2: ")
# create function
def sum(num1,num2):
return num1 + num2
# call the function
answer = sum(int(number1), int(number2))
print(answer)
The output:

We finished covering the basics of functions in Python. You can try out creating functions to do different tasks. And also, the returned value from the function can be used further in your program. Functions are there to make your coding life easy. Once you get a problem to solve, what you need to do is identify the tasks that you can create functions for. It will make it much easier to come up with a solution. By breaking the problem into creating several functions, you can improve the readability of your code as well.
I hope you got a good understanding of functions in Python. Practice more examples and get familiar with functions.
Python
Loops in Python | A Step by Step Guide
Welcome back, everyone! Hope you’re having fun with our Python lesson series. This lesson is all about loops in Python. Loops play a big role in programming, and you can do a lot with them. Loops are used to iterate through the same block of code over and over again. There are two main categories of loops. They are known as “for loops” and “while loops”. Both of them will be very useful for you in the future. Let’s begin with for loops.
For Loops in Python
A for loop is used for iterating over a sequence. Remember how we talked about lists in Python in a previous lesson? Well, iterating through a list and accessing the elements can be done by using a for-loop. You can use for-loops not only with lists but also with other sequences like tuple, dictionary, set, or a string. A for loop is used when we know how many times that it should iterate. Take a look at the below examples.
# Iterate through a list
#create a list
friends = ["Kevin","Ariana","Kyle","John","Tim"]
#for loop to print each friend
for friend in friends:
print(friend)
The output:

Pay attention to the syntax. After the keyword “for”, you are free to use any variable name. After the keyword “in”, the name of the list should be used. Then, in the end, a semicolon is used. Remember how we talked about indentation in the previous lesson? The lines of code which should be inside the scope of the for-loop must have an indentation. In the same manner, you can iterate through a string and access each character as well.
#Iterate through a string
for letter in "Elephant":
print(letter)
The output:

By using the range function, a range can be specified in a for loop.
#use of range function
for index in range(5):
print(index) # 0 to 4 will be printed excluding 5
The output:

for index in range(5,10):
print(index) # 5 to 9 will be printed excluding 10
The output:

for index in range(5,10,2):
print(index)
The output:

Just like we use a for loop to iterate through a list, we can use nested for loops to iterate through two-dimensional lists. A nested for loop is when you have a for loop inside another for loop. Look at the below example.
#create a 2D list
number_grid = [ [10,20,30], [40,50,60], [70,80,90]]
#nested for loop
for row in range(len(number_grid)):
for column in range(len(number_grid[row])):
print(number_grid[row][column])
The output:

While Loops in Python
Now that you have a basic understanding of loops let’s look into while loops. A while loop is executed as long as the given condition is true. It is mostly used when we are not certain about how many times it should be iterated. Look at the below code and understand the syntaxes and the functionality.
i = 1
while i <5:
print(i)
i = i + 1
The output:

In the above example, we have assigned the value 1 to the variable i. Then in the while condition, it is checked whether i is less than 5. Since it is true, the code inside the while block is executed. Likewise, it will print values from 1 to 4. Once 4 is printed, the value of i becomes 5. Then, the condition becomes false. Therefore, the while loop stops.
So up to now, we’ve finished covering the basics of loops in Python. Now, we’re going to explore some further concepts attached to loops. Those are break statements and continuous statements. The break statement can be used to stop the loop even if the while condition is true. Look how the above example is modified by adding a break statement. Because of it, only 1 & 2 will be printed as outputs (Once i becomes 3, the break statement executes).
i = 1
while i <5:
if i==3:
break
print(i)
i = i + 1
The output:

With the continue statement, we can stop the current iteration, and continue with the next.
i = 0
while i <5:
i = i + 1
if i==3:
continue
print(i)
The output:

Because of the continue statement, the program prints values from 1 to 5, excluding 3. These break statement and continue statements can be used with for loops as well with the same functionality. These points must be enough for a good insight into loops in Python.
So we hope that you got a good understanding of loops in Python. Keep practicing until the next lesson!
-
Tech5 years agoHow to Use Find My iPhone I The Easiest Way!
-
Tech5 years ago11 Best Battle Royale Games for Low End PC 2021
-
Reviews5 years agoFastrack Reflex 3.0 Review 2024: Should You Buy?
-
Python6 years agoPython if Statements | Easy Explanation and Examples
-
Tech5 years ago15 Best Free Live Football Streaming Apps for Android & IOS
-
Tech5 years ago11 Best Free Scanner Apps for iPhone
-
More6 years agoTop 7 Reasons to Learn Java in 2024
-
Tech5 years agoUsers Can Operate One WhatsApp Account on Various Devices, Multi-Device Feature Will Be Coming Shortly!
