Python for loop with List

We will see in this tutorial how to use the Python for Loop with list.

The list is the group of elements. In which different types of elements are stored according to the index number. You will also read about arrays when you discuss array modules and  NumPy packages. Which is a lot like the Python list.

But the main difference between them is that you can put elements of different data types in the list but you can’t put elements of different data types in the array. So, you have to put elements of the same data type.

And the list is a mutable object because you can modify the elements stored in the list.

Python List indexing

List indexing here means splitting the list into parts according to the index. Each element in the list has a specific index number. So you can access every element of the list according to the index number.

The index number will always start from zero and if you want to access the elements of the list in a negative way, you have to start from -1. So look at this image below.

syntax of python for loop with index

 

How to access each element of the list by index number.

int_list = [4, 8, 12, 16]
print(int_list[0])
print(int_list[1])
print(int_list[2])
print(int_list[3])

Output :

4
8
12
16

How do you split the list into smaller parts?

Company_list = ['amazon', 'google', 'fb', 'netflix', 'adobe']
print(Company_list[0:2])
print(Company_list[1:4])
print(Company_list[2:4])
print(Company_list[3:4])

Output :

['amazon', 'google']
['google', 'fb', 'netflix']
['fb', 'netflix']
['netflix']

How do you split the list into parts from the opposite side?

Company_list = ['amazon', 'google', 'fb', 'netflix','adobe']
print(Company_list[-3:-1])
print(Company_list[0:-1])
print(Company_list[-3:4])
print(Company_list[::-1])

Output :

['fb', 'netflix']
['amazon', 'google', 'fb', 'netflix']
['fb', 'netflix','adobe'] 
['adobe','netflix', 'fb', 'google', 'amazon']

Convert List to another Data type

You can convert the list to another data type with the help of different functions. So, you look at these problems below.

Company_list = ['amazon', 'google', 'fb', 'netflix', 'adobe']
Company_number = [0, 1, 2, 3, 4]
print(tuple(Company_list))
print(set(Company_list))
print(dict(zip(Company_list,Company_number)))

Output :

('amazon', 'google', 'fb', 'netflix', 'adobe')
{'google', 'netflix', 'adobe', 'fb', 'amazon'}
{'amazon': 0, 'google': 1, 'fb': 2, 'netflix': 3, 'adobe': 4}

When you convert a list to a set, the set will not accept duplicate elements in the list.

int_list = [12, 15, 12, 15, 18, 18,20]
print(set(int_list))

Output :

{18, 12, 20, 15}

In the same way you can convert sets and tuples to lists

Set_number = { 4, 6, 8, 9 }
tuple_number = (1, 3, 4, 8)
print(list(Set_number))
print(list(tuple_number))

Output :

[8, 9, 4, 6]
[1, 3, 4, 8]

Below we will learn about some important methods. And let’s look at how these are being applied to the list as an example.

1. append () method

If you want to add an element at the end of the existing list, you need to use the append method.

Number_list = [0, 1, 2]
Number_list.append(3)
Number_list.append(4)
Number_list.append(5)
print(Number_list)

Output :

[0, 1, 2, 3, 4, 5]

Notice above that I first put the elements 0, 1, and 2 in the list and now some elements have been added to it so now the elements in the list are 0 to 5.

2. insert () method

The insert method will work a lot like the append method but if you want to insert an element in the list you have to specify the particular position where you want to place the element.

companies = ['google', 'adobe', 'amazon']
companies.insert(1,'facebook')
companies.insert(2,'netflix')
print(companies)

Output :

['google', 'facebook', 'netflix', 'adobe', 'amazon']

The index number is the position of the element. Notice the problem above. Adobe was in index number 1 but I inserted Facebook in that place. As a result, Adobe's index number is 2. The second time I inserted Netflix in position 2, then adobe's position will be 3.

3. pop method

If you want to remove an element from the end of an existing list, you can use the pop method.

companies = ['google', 'adobe', 'amazon']
companies.pop()
print(companies)
companies.pop()
print(companies)

Output :

['google', 'adobe']
['google']

You can also remove the specified element using the pop method. For this you need to pass the index number of that specified element in the pop() function.

companies = ['google', 'adobe', 'amazon']
companies.pop(1)
print(companies)
companies.pop(0)
print(companies)

Output :

['google', 'amazon']
['amazon']

Here Adobe, the first index number, has been removed using the pop method. And for the second time, Google, located in the index number 0, has been removed.

4. remove method

With the help of Remove method you can remove a particular element in the list. Here, when you want to remove the element from the list, pass it to the Remove function and you will see that the element has been automatically removed from the list.

companies1 = ['google', 'adobe', 'amazon']
companies1.remove('google')
print(companies1)
companies1.remove('amazon')
print(companies1)

Output :

['adobe', 'amazon']
['adobe']

Here you will notice that Google has been removed from the list first and Amazon has been removed a second time.

5. reverse method

If you want to arrange each element of the list in reverse order, you need to take the help of reverse method.

companies = ['google', 'amazon', 'adobe', 'netflix']
companies.reverse()
print(companies)

Output :

['netflix', 'adobe', 'amazon', 'google']

Python for loop with List

You should always use iterable objects with Python for Loop. The list here is an iterable object so each element in the list is arranged according to the specified sequence. Notice that the syntax for the loop is given below.

Syntax of Python for loop with list

You can also use the list with the range function without using the for loop directly. Here for loop will return the index number of each element in the list. And using those index numbers, you can perform different tasks in For Loop.

Syntax of for loop with list through range function

You can also access each element of the list using the next () and iter () functions which will act as a whole for loop. The next function here will turn the iterable object into an iterator and you can access each element one by one from this list iterator. So, notice the whole process below which will work like a whole for loop.

 Python for loop with list Examples

Above we have discussed all the concepts that can be used with Python for Loop. Again, we will solve some Python for loop related problems.

1. How you access each element of the list.

companies = ['Google', 'Amazon', 'Netflix', 'Adobe']
for var in companies:
    print(var)

Output :

Google
Amazon
Netflix
Adobe

2. How to convert elements from first list to second list with the help of for loop.

companies = ['Google', 'Amazon', 'Netflix', 'Adobe']
companies1 = []
for var in companies:
    companies1.append(var)
print(companies1)

Output :

['Google', 'Amazon', 'Netflix', 'Adobe']

3. Suppose the list contains elements of integer and float data type. How you display the sum of the elements in the list on the screen.

numbers = [2, 3, 6, 8, 7.6, 9.7]
sum=0
for var in numbers:
    sum+=var
print(sum)

Output :

36.3

4. How do you access the elements of a list from the opposite direction?

companies = ['Google', 'Amazon', 'Netflix', 'Adobe']
for var in reversed(companies):
    print(var)

Output :

Adobe
Netflix
Amazon
Google

5. How to put an element in an empty list with the help of For Loop.

companies = []
for var in range(4):
    companies.append(input())
print(companies)

Output :

Google
Adobe
Facebook
Amazon 
['Google', 'Adobe', 'Facebook', 'Amazon ']

6. How do you check if a particular element is stored in the list?

companies = ['Google', 'Amazon', 'Netflix', 'Adobe']
print('fb' in companies)
print('Google' in companies)
print('Amazon' in companies)

Output :

False
True
True

7. How do you convert elements from a list with different data types into a list with the same data type?

List_elements = [1, 2.7, 3,'4', 5,'google', 7+0j, 9.0, 10j ]
elements1,elements2,elements3,elements4=[],[],[],[]
for element in List_elements:
    if type(element) == str:
        elements1.append(element)
    elif type(element) == float:
        elements2.append(element)
    elif type(element) == int:
        elements3.append(element)
    else :
        elements4.append(element)
print(elements1, elements2, elements3, elements4)

Output :

['4', 'google'] [2.7, 9.0] [1, 3, 5] [(7+0j), 10j]

8. How do you display the list elements and index numbers together on the screen.

companies = ['Google', 'Amazon', 'Netflix', 'Adobe']
for var in range(len(companies)):
    print(f'index number {var} ----> company {companies[var]}')

Output :

index number 0 ----> company Google
index number 1 ----> company Amazon
index number 2 ----> company Netflix
index number 3 ----> company Adobe

9. Suppose there are 1 to 10 integers in the list. How to make a tuple with even integer numbers from the list.

number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = []
for var in number_list:
    if var%2==0:
        even_list.append(var)

print(tuple(even_list))

Output :

(2, 4, 6, 8, 10)

11. How do you access the 2d list elements?

companies = [['google', 'facebook'], ['amazon', 'adobe'], ['flipkart', 'apple']]
for i in companies:
    for j in i:
        print(j)

Output :

google
facebook
amazon
adobe
flipkart
apple

List Comprehension

If you look at some examples before you know the definition of list comprehension, then you can easily understand how list comprehension works.

Here we will create a list using Python for Loop. In which the number of integers from 1 to 5 will be present.

int_list = []
for var in range(1,6):
    int_list.append(var)
print(int_list)

Output :

[1, 2, 3, 4, 5]

The above problem is now solved with the help of list comprehension.

int_list =[var for var in range(1,6)]
print(int_list)

Output :

[1, 2, 3, 4, 5]

So, you see, with the help of list comprehension, the code of more than one line is converted to single line code. And a new list will always be created during list comprehension. So, below you will see different types of examples where the condition is being used.

How do you make a list of even numbers from 0 to 10?
First we will solve the problem without using list comprehension.

even_list = []
for var in range(0,11,2):
    even_list.append(var)
print(even_list)

Output :

[0, 2, 4, 6, 8, 10]

And you can solve this problem in two ways with the help of range function.

First you use the range function where you put the value two of the step argument.

even_list1 = [var for var in range(0,11,2)]
print(even_list1)

Output :

[0, 2, 4, 6, 8, 10]

Second, you can use if condition using the range function.

even_list2 = [var for var in range(0,11) if var%2==0]
print(even_list2)

Output :

[0, 2, 4, 6, 8, 10]

How do you convert elements of a string to elements in a list?

str_list = [var for var in 'pythongalaxy']
print(str_list)

Output :

['p', 'y', 't', 'h', 'o', 'n', 'g', 'a', 'l', 'a', 'x', 'y']

How do you create a second list with the first letter of the elements in another list?

companies=['facebook', 'adobe', 'netflix', 'google']
companies1=[com[:1].upper() for com in companies]
print(companies1)

Output :

['F', 'A', 'N', 'G']

How do you create a separate list of digits from strings. But here the string is made up of a combination of digits and letters?

String = 'Python09873456Galaxy'
digit_list = [var for var in String if var.isdigit()]
print(digit_list)

Output :

['0', '9', '8', '7', '3', '4', '5', '6']

FAQ’S

What is the list ?

The list is a group of elements where you can store elements of different data types. And the list is a mutable object so you can modify the elements of the list.

How do you prove that a list is an iterable object ?

Iterable objects are those objects whose elements are arranged according to the sequence.

You can use the directly iterable object in the for loop. So, if you can convert an object to iterator with the help of iter function, then it is an iterable object.

You will also see that the elements of the iterable object are arranged according to the sequence. That is, you can access according to the index number. Such as list.

What is the main difference between a list and an array ?

You can store any type of data in the list. But you have to keep the same type of data in the array.

Why use for loop in the list ?

For loop is used to perform the same task repeatedly. So, we have to perform some tasks in the list when it is necessary to repeat the same task, then we will use loop with the list instead of repeating the same task.

What is list comprehension and why is it used for list operations ?

List comprehension is a process of creating new lists. Where there is no need to write multiple line code. So, with the help of list comprehension, you can convert multiple line code into one line code.

Below we will see an example where we will create a new list of odd numbers from 1 to 10.

odd_list = []
for var in range(1,11,2):
    odd_list.append(var)
print(odd_list)

Output :

[1, 3, 5, 7, 9]

The above problem is solved with the help of list comprehension.

odd_list=[var for var in range(1,11,2)]
print(odd_list)

Output :

[1, 3, 5, 7, 9]

How do you create a list of float number sequences ?

If you were called an integer sequence, you would use the range function. But you can’t create a float number sequence with the range function. Here you need to use the arange() function which is located inside the NumPy package. And the arange() function will work just like the range function.

Conclusion

In this tutorial, I have tried to explain the whole concept by solving enough problems. So, don’t forget to share if you like it. If there is a mistake here, please comment so that I can correct my mistake. You can also use the Python documentation.

Leave a Comment

Your email address will not be published. Required fields are marked *