That creates a list of one element with just the node object. Presumably results is expected to be a list.
Variable points to a nested list, where length of outer as well as inner list is 1.
In [9]: lst = [[1]]
In [10]: len(lst)
Out[10]: 1
In [11]: len(lst[0])
Out[11]: 1
Appending list to an empty list,
In [12]: lst = []
In [13]: lst.append([1])
In [14]: lst
Out[14]: [[1]]
It depends on what data type some_var is holding. If some_var is a primitive data type, say integer, then lst is a list of list of an integer. But if some_var is a list itself, then lst is a list of list of list
double square brackets side by side in python - Stack Overflow
function - Python variable in the square brackets does not work - Stack Overflow
regex - Python Parsing with a Variable Name and Square Brackets - Stack Overflow
python - How to print a value from a variable in square brackets? - Stack Overflow
Videos
If you have a list
l = ["foo", "bar", "buz"]
Then l[0] is "foo", l[1] is "bar", l[2] is buz.
Similarly you could have a list in it instead of strings.
l = [ [1,2,3], "bar", "buz"]
Now l[0] is [1,2,3].
What if you want to access the second item in that list of numbers? You could say:
l[0][1]
l[0] first gets you the list, then [1] picks out the second number in it. That's why you have "square bracket next to square bracket".
Square brackets are used to define lists, but also to get things from lists.
When you have a list of lists and want something from an inner list, you need to get that inner list (using brackets) and then get the desired thing inside (using brackets again).
lol = [[1, 2, 3], [4, 5, 6]]
lol[1]
# [4, 5, 6]
lol[1][0]
# 4
This should work:
int_digit = int(digit)
print(int_digit) # not necessary, leave this if you want to print the user input as an integer
print(text1[int_digit-1])
Not really much to explain here, it's just how python works.
You need the -1 at the end, because this function grabs by index (which starts at 0)
I'm quite new into Python and to programming in general, but this is how I'd solve the problem:
letter = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
digit = int(input())
print(letter[digit])
Try this regex:
^\[(?!END).*]
Regex live here.
Explaining:
^\[ # starts with a '[' character
(?!END) # don't match 'END'
.*]$ # take all till the end ']' character
Hope it helps.
I believe that the question that you have asked can be answered using the solution provided here with only slight modifications. As the linked answer is so thorough, I will not repeat the answer, but if for some reason that does not work, let me know and I can provide some alternatives.
msg = "John" + " ["+ last +"] "
Python interprets quotes as a string delimiter - anything inside quotes is treated as a string, not as python code.
So here, " [" is a string, so the plus is required for string concatenation.
Think of it like this.
last = "Smith"
msg = "John"
msg = msg + " ["
msg = msg + last
msg = msg + "] "
print(msg)
If it helps, add print(msg) after each assignment to msg and see how it develops.
There are many, many, many other ways to do this. See How do I put a variable inside a string?
They are part of the Python syntax and unlike using single (') or double (") quotes, they can pretty much never be interchanged.
Square and rounded brackets can mean so many different things in different circumstances. Just to give an example, one may think that both the following are identical:
a = [1,2,3]
a = (1,2,3)
as a[0] gives 1 in both cases. However, the first one is creating a list whereas the second is a tuple. These are different data types and not knowing the distinction can lead to difficulties.
Above is just one example where square and rounded brackets differ but there are many, many others. For example, in an expression such as:
4 * ((12 + 6) / 9)
using square brackets would lead to a syntax error as Python would think you were trying to create a nested list:
4 * [[12 + 6] / 9]
So hopefully you can see from above, that the two types of brackets do completely different things in situations which seem identical. There is no real rule of thumb for when one type does what. In general, I guess that square brackets are used mainly for lists and indexing things whereas rounded brackets are for calculations (as you would in maths) and functions etc.
Hope this helps you out a bit!
It's hard to answer succinctly, but I can give you some common examples.
Square brackets define lists:
my_list = [1, 2, 3, 4]
They are also used for indexing lists. For instance:
print(my_list[1])
Returns 2.
Additionally, they are frequently used to index dictionaries, which are defined with curly brackets:
my_dict = {5:'a', 6:'b', 7:'c'}
The indexing for dictionaries requires that I input the "key" as follows:
print(my_dict[6])
Returns b.
Functions are called using round brackets. For instance, if I want to add an element to my list, I can call the append() function:
my_list.append(8)
I have just added 8 to my list. You will notice that when I called the print function I also used curved brackets.
This is by no means comprehensive, but hopefully it will give a starting point.
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
One interesting difference :
lst=[1]
print lst // prints [1]
print type(lst) // prints <type 'list'>
notATuple=(1)
print notATuple // prints 1
print type(notATuple) // prints <type 'int'>
^^ instead of tuple(expected)
A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).
It means to extract the first item in the list/tuple return by the function.
In [1]: "this is a long sentence".split()
Out[1]: ['this', 'is', 'a', 'long', 'sentence']
In [2]: "this is a long sentence".split()[0]
Out[2]: 'this'
This means that return value of the wait function is either list or tuple and 0 it is an index of the element from this output. For example:
def func(numericValue):
return list(str(numericValue))
res = func(1000)
res[0] - > 1
Or:
def convert(value, to_type):
#do something
return resuls, convertedValue
res = convert(1100, str)
res[0] - > True
If this is just for the purposes of printing, you can do:
list_o_lists_o_lists = [[['--w'], ['ww-'], ['bbb']], [['w--'], ['-ww'], ['bbb']]]
print(*list_o_lists_o_lists, sep=", ")
which unpacks the outer list into its two inner lists as sequential arguments to print, which prints each separately, while sep=", " tells print to place a comma and space between each of them, getting the display you want, but making no change to the data structure.
But otherwise, what you want isn't possible as stated; removing the outer brackets leaves you with two elements that need to be stored in something. The literal with those brackets removed is a tuple:
[['--w'], ['ww-'], ['bbb']], [['w--'], ['-ww'], ['bbb']]
but the repr of a tuple includes parentheses, so you'd just be replacing the outer brackets with parens if you printed it without special formatting effort:
>>> [['--w'], ['ww-'], ['bbb']], [['w--'], ['-ww'], ['bbb']]
([['--w'], ['ww-'], ['bbb']], [['w--'], ['-ww'], ['bbb']])
Your description doesn't match your desired output. Your desired output has the inner brackets removed, not the outer ones. To remove the inner brackets, you can do
[[item[0] for item in inner_list] for inner_list in outer_list]
Hello,
Please review the code in bold.
My question is in both examples,
Example 1.
python_topics = ["variables", "control flow", "loops", "modules", "classes"]
length = len(python_topics)
index = 0
while index < length:
print("I am learning about " + python_topics[index])
index += 1
Example 2.
favorite_fruit = "blueberry"
last_char = favorite_fruit**[len(favorite_fruit) - 1]**
Output: Y
My question is, their a way to describe what the square brackets are doing? Would you say that the square brackets are used to access or transfer the value of the variable? Hopefully this question makes sense. Thank you very much.
Everything that is in square brackets is optional, i.e. you can omit it. If the square brackets contain more than 1 argument, you can't choose which ones to omit, you must either specify all of them, or none.
That's where nested brackets come in handy:
int([x[, base]])
Here, for example, you can use int() without arguments (by omitting the whole outer bracket) or int(x) (by omitting the inner bracket) or int(x, base). But not int(base) (well, that would just mean int(x)).
This isn't actual Python syntax, just a way for documentation to be clearer. Python 3's documentation tries to avoid these brackets.
These are optional arguments. You need not specify them, but you may want to use them for specific functionality.
When one or more top-level parameters have the form parameter = expression, the function is said to have โdefault parameter values.โ For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameterโs default value is substituted. If a parameter has a default value, all following parameters must also have a default value โ this is a syntactic restriction that is not expressed by the grammar.
source
whenever you use squared brackets you are defining a list (an array)
when you call a function (like random.choice ) need to use () to pass arguments
so in this case you are calling a function over a list the equivalen should be:
def play():
user = input(" 'r' for rock, 'p' for paper, 's' for scissors: ")
myList = ['r','p','s']
random.choice(myList)
if user == computer:
return "tie"
this is a paper scissor rock game where the only response is to tie. the random.choice function select one element from an input List
The square brackets are actually a very simple term in python known as a list.
The code above could also translate to:
import random #Import random module
userinput = input(" 'r' for rock, 'p' for paper, 's' for scissors: ") #ask user what they want to input
choicelist = ['r', 'p', 's'] #List of options
computer = random.choice(choicelist) #pick a random option from list
if user == computer: #checking if they are both the same
print("tie") #return tie if equal (Also this was a return which only works in functions, but i removed the function because it was not needed)
Please comment if you have any more questions!
You want to define the special __getitem__[docs] method.
class Test(object):
def __getitem__(self, arg):
return str(arg)*3
test = Test()
print test[0]
print test['kitten']
Result:
000 kittenkittenkitten
Python's standard objects have a series of methods named __something__ which are mostly used to allow you to create objects that hook into an API in the language. For instance __getitem__ and __setitem__ are methods that are called for getting or setting values with [] notation. There is an example of how to create something that looks like a subclass of the Python dictionary here: https://github.com/wavetossed/mcdict
Note that it does not actually subclass dictionary and also, it has an update method. Both of these are necessary if you want your class to properly masquerade as a Python dictionary.