Python: Array v. List

111,647

Solution 1

Use lists unless you want some very specific features that are in the C array libraries.

python really has three primitive data structures

tuple = ('a','b','c')
list = ['a','b','c']
dict = {'a':1, 'b': true, 'c': "name"}

list.append('d') #will add 'd' to the list
list[0] #will get the first item 'a'

list.insert(i, x) # Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).    

list.pop(2) # will remove items by position (index), remove the 3rd item
list.remove(x) # Remove the first item from the list whose value is x.

list.index(x) # Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x) # Return the number of times x appears in the list.

list.sort(cmp=None, key=None, reverse=False) # Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse() # Reverse the elements of the list, in place.

More on data structures here: http://docs.python.org/tutorial/datastructures.html

Solution 2

Nothing really concrete here and this answer is a bit subjective...

In general, I feel you should use a list just because it is supported in the syntax and is used more widely in the other libraries, etc.

You should use arrays if you know that everything in the "list" will be of the same type and you want to store the data more compactly.

Share:
111,647
tkbx
Author by

tkbx

Human

Updated on February 02, 2020

Comments

  • tkbx
    tkbx over 4 years

    Possible Duplicate:
    Python List vs. Array - when to use?

    I'm working on a few projects in Python, and I have a few questions:

    1. What's the difference between Arrays and Lists?
    2. If it's not obvious from question 1, which should I use?
    3. How do you use the preferred one? (create array/list, add item, remove item, pick random item)
    • Matt Alcock
      Matt Alcock about 12 years
      This feels more like a tutorial request rather than a question however see my notes below. Please vote up and/or accept if appropriate
  • wim
    wim about 12 years
    don't forget sets ..
  • Matt Alcock
    Matt Alcock about 12 years
    correct there are also sets. collections with no repeating items. docs.python.org/tutorial/datastructures.html#sets