Wednesday, June 9, 2021

Array

An Array is a collection of items or elements all having the same datatypes. An element from an array can only be accessed from its index value. 

How to Initialize an Array in Python? (with Code) | FavTutor

Example: Let’s create an array of cars.

cars = [“Kia”, “Toyota”, “Ford”, “Tesla”]

 

In order to get the value Ford as output, we need to write print (cars [ 2 ] ) 

In Python, a List is very similar to an Array . It contains a list of elements separated by commas and its elements are written with square brackets [ …. ] .

A value from a List can be accessed from its index value and the syntax is-
List_name [ index_num ]

Now see the code below:

 

After running the above piece of code, we get an output of:

 

In the above piece of code, fruits is a List containing 6 elements. The value at position 0 is “apple ”, at position 1 is “orange ” and so on. 

x is a variable holding a string value. The value at position 0 is “t” , at position 1 is “h ” and so on.

len( ) function is used to get the length of the list .

In Line 4 and 5 we are performing Slicing operation. 

print ( fruits [ 2 : 4] ) means print elements from position 2 (including its value ) to position 4 (excluding its value ).

 

Output: [‘banana’, ‘mango’]

print ( x [ 2 : 8 ] ) means print the values of x (“this apple is tasty ”) from position 2 (including its value ) to position 8 (excluding its value ). 

 

Output: is app

In the next post we will see how to insert and delete data in to an array

Share:

0 comments:

Post a Comment