Accessing elements using for loop In Python

Accessing elements using for loop In Python

Author:
Price:

Read more

 Introduction to List


                Python programming language has four collections of data types such as List, Tuples, Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an ordered collection of values enclosed within square brackets [ ]. Each value of a list is called as element. It can be of any type such as numbers, characters, strings and even the nested lists as well. Th e elements can be modifi ed or mutable which means the elements can be replaced, added or removed. Every element rests at some position in the list. Th e position of an element is indexed with numbers beginning with zero which is used to locate and access a particular element. Th us, lists are similar to arrays

Programming in Python

                                            In Python, programs can be written in two ways namely Interactive mode and Script mode. The Interactive mode allows us to write codes in Python command prompt (>>>) whereas in script mode programs can be written and stored as separate file with the extension .py and executed. Script mode is used to create and edit python source file

 Create a List in Python

                                            In python, a list is simply created by using square bracket. Th e elements of list should be specifi ed within square brackets. Th e following syntax explains the creation of list.

Accessing elements using for loop

                                      In Python, the for loop is used to access all the elements in a list one by one. This is just like the for keyword in other programming language such as C++.

          Syntax:

                       for index_var in list:

                       print (index_var)

                                          Here, index_var represents the index value of each element in the list. Python reads this “for” statement like English: “For (every) element in (the list of) list and print (the name of the) list items”

Example:

                     Marks=[23, 45, 67, 78, 98] 

                     for x in Marks: 

                     print( x )

 Output 

         23

         45

         67 

         78

         98

                                 In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The Python reads the for loop and print statements like English: “For (every) element (represented as x) in (the list of) Marks and print (the values of the) elements”

0 Reviews