Python arrays and lists

Arrays are a set of multiple values of the same type. A list is a set of values and can be of different types. For example an array can contain values only of integers, strings, char or float. A list can contain values of different types like integers and strings. In the following program * is used to import whole array module. An array of floating numbers is created. Here in the syntax ‘d’ represents the data type which is float. Next to data types are the array elements. In the output array elements are printed. Array elements starts with first element of index ‘0’.   

from array import*

numbers = array('d',[1.8 , 3.1 ,2.87,5.84,9.1])

print(numbers)

print(numbers[1:3])

 Output :

 array(‘d’, [1.8, 3.1, 2.87, 5.84, 9.1])
 array(‘d’, [3.1, 2.87])

In the following program for loop is used to display the array elements.

from array import*

numbers = array('d', [1.8, 3.1, 2.87, 5.84, 9.1])

print("The values of numbers in the array are ")

for x in numbers:

print(x)

 Output :

 The values of numbers in the array are
 1.8
 3.1
 2.87
 5.84
 9.1

List can contain elements of different data types. Lists are created in python  using square bracket and the different list elements are separated with comma. Lists can also contain duplicate items. Elements are indexed in the list with first item ‘0’.

Mylist = ["Apple", 30.85, True, 47, "Apple"]

print(Mylist)

 Output :

 [‘Apple’, 30.85, True, 47, ‘Apple’]

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments