4

Whenever I try to create an empty list in python, I realized that if I do not know and define the range of it, I can't set a value to whatever indice I want like in R.

q = list()
q[ 2 ] = 9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

But in R, it does not happen.

Q = c( )
Q[ 4 ] = 3
>>> [1] NA NA  4

Is there any equivalent operation that I can do in python?

Nihat
  • 97
  • 7
  • 1
    R array and vector types are pretty different from python lists. – juanpa.arrivillaga Oct 30 '19 at 21:25
  • Maybe adding context on why you want to do that in python could help to find the right expression. Moreover, please, notice how python and R are using different indexing. Python starters at 0 (first element) where R starts at 1 (first element). – daniel_hck Dec 08 '20 at 15:19

2 Answers2

5

The c function in R is a function which concatenates its arguments as lists. You can concatenate two lists in Python using +; to concatenate a variable number of lists, as c in R does, you can use the sum function. This normally adds numbers, but can be used to add lists by "starting" from an empty list instead of from 0:

>>> lists = [[1,2,3], [4,5,6], [7,8,9]]
>>> sum(lists, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

However, this is unrelated to the error in your code. The problem is that in Python, you can only use the syntax mylist[i] = x to set a new value at an index which already exists. Since you created an empty list, it has no elements so the index 2 is out of bounds.


If you want to be able to set values at arbitrary indices, which don't necessarily form a contiguous range, you could use a dictionary:

>>> q = dict()
>>> q[2] = 9

However, there will be a mismatch between what some operations do and what you expect them to do for a list-with-some-unset-values; for example, len(q) gives the number of elements which are set, rather than the length of the sequence including the unset values.

kaya3
  • 47,440
  • 4
  • 68
  • 97
1

In python, the correct way of adding items to a list is by append.

mylist.append(element)

otherwise, you can use list comprehension for generating a list of None or empty strings:

mylist= [None for i in range(100)]

this will generate a list with 100 Nones. Then you can assign by index:

mylist[2] = 4
paltaa
  • 2,985
  • 13
  • 28