hi guys
wat if List is equivalent 2 Arrays in c
or do we have Arrays seperately defined in python??

Recommended Answers

All 5 Replies

We don't have separately defined arrays. Lists are the closest thing we got, I believe.

There is a library called NumPy that implements C arrays for python. The only limitation ( I think ) is that they must be arrays of numbers.

Oh yes, Python has an array type, but you must import module array:

# module array has Python's array type

import array

# Python25 use 'c' as the character typecode
# Python30 uses unicode character typecode 'u'
char_array = array.array('c', 'hello world')

print(char_array[0])    # h
print(char_array)       # array('c', 'hello world')

# 'i' uses a signed integer of 2 bytes
int_array = array.array('i', [2, 4, -11])

print(int_array[2])     # -11
print(int_array)        # array('i', [2, 4, -11])

# 'f' uses 4 bytes and 'd' uses 8 bytes per element 
float_array = array.array('d', [1.0, 2.0, 3.14])

print(float_array[2])  # 3.14

for n in float_array:
    print(n)


# get more information on module array
help('array')

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time. Arrays use up less space in memory, for a limited number of applications this is important.

commented: You knowledge of Python is astounding +5

Erm, oops?

One more thought: lists of lists in Python function reasonably well as arrays:

mylist = [[1,2,3],[4,5,6],[7,8,9]]

print mylist[0][2]
3

I say "reasonably well" -- there aren't any linear algebra methods that can be used on lists of lists (like det(), inv(), or eigenvalues()), but the LinearAlgebra module covers that.

Jeff

thanx ene and jrcagle...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.