SoFunction
Updated on 2024-10-29

Examples of [] Usage in Python

[] is a bridge to get parameters from outside the program, this "outside" is very critical, so those who try to explain it from the code to explain the role of the explanation has not been clear. Because we can take more than one parameter from outside the program, we get a list, which can actually be seen as a list, so we can use [] to extract its elements. The first element is the program itself, followed by the externally given parameters.

as below

import sys
a = [0]
print(a)

Save and run as follows

The result obtained is that this is what 0 means by the code (i.e. this .py program) itself.

Then we change 0 to 1 in the code :

import sys
a = [1]
print(a)

runs and outputs the parameters we passed in, so [] is what gets the parameters we passed in from the console

Next, let's change the code a bit to get the full parameters of the inputs

import sys
a = [1:]
print(a)

The results obtained are ['11', '22', '33', '44', '55']

In fact, it is a list of items for the user input parameters, the key is to understand that this parameter is input from outside the program, rather than the code itself somewhere, to see the effect of it should save the program, from the outside to run the program and give parameters.

P.S. Python reads the parameters of a command line using the

#!/usr/bin/python
 
import sys
 
print "Script Name:", [0]

The above code prints out the name of the executable program, together with the len() function, you can know how many arguments are input to the instruction. Here is how to use len() function to print out the input parameters.

#!/usr/bin/python

import sys

n = len()
for i in range(1, n):
  print [i]

summarize

to this article on Python [] usage of the article is introduced to this, more related Python [] usage content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!