Home | | Problem Solving and Python Programming | List as array - Python

Syntax, Example - List as array - Python | Problem Solving and Python Programming : Control Flow, Functions

Chapter: Problem Solving and Python Programming : Control Flow, Functions

List as array - Python

Array is a collection of similar elements. Elements in the array can be accessed by index.

List as array:

Array:

 

Array is a collection of similar elements. Elements in the array can be accessed by index. Index starts with 0. Array can be handled in python by module named array.

To create array have to import array module in the program.

 

Syntax :

import array

 

Syntax to create array:

Array_name = module_name.function_name(‘datatype’,[elements])

 

example:

a=array.array(‘i’,[1,2,3,4])

a- array name

array- module name

i- integer datatype

 

Example

 

Program to find sum of array elements

import array

sum=0

a=array.array('i',[1,2,3,4])

for i in a:

sum=sum+i

print(sum)

 

Output

10

 

Convert list into array:

 

fromlist() function is used to append list to array. Here the list is act like a array.

 

Syntax:

arrayname.fromlist(list_name)

 

Example

 

program to convert list into array

import array

sum=0

l=[6,7,8,9,5]

a=array.array('i',[])

a.fromlist(l)

for i in a:

                  sum=sum+i

print(sum)

 

Output

35

 

Methods in array

a=[2,3,4,5]


 

Tags : Syntax, Example , Problem Solving and Python Programming : Control Flow, Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : List as array - Python | Syntax, Example


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.