Python Code Example: Converting Array to List in Python

To convert a call in Python to C, you can construct a corresponding structure. However, it is often simpler and clearer to use Python objects instead of explicit functions, especially when you intend to keep the code readable. Sharing data between C types and Python types can pose a challenge in such situations.

Solution 1:

The contents of


consist of strings and are not analyzed as literals within the program.

Simply provide a string separated by commas, but exclude the enclosing brackets.

python3 1,2,3,4,5 0

Transform the input into an array by applying


to it.

import sys
arr = sys.argv[1].split(',')

Solution 2:

Strings are the only acceptable format for commandline arguments. In order to utilize integers, they must be converted to


. If you choose to use the list syntax as demonstrated in the example, a parser must be used (either your own, one from


, or


— but not


). However, there is a simpler solution: write each argument separately and use a slice of


as your list. Passing multiple arguments to a commandline program (such as multiple filenames for




, etc.) is typically done using space separation.

python3 -n a b c 1 2 3

Initially, you would single out and exclude the arguments that serve a distinct function (as depicted in the aforementioned example with


), and subsequently retain the remaining ones.

arr = sys.argv[2:]
print(arr[3])   # Prints "1"

It is important to ensure that any argument from the shell is protected by using quotes to avoid any characters with special meaning (such as




), as well as spaces that are included as part of an argument. However, this issue should be addressed separately.

Frequently Asked Questions