+ 1
What is ':' in python?What are its uses?
I have seen ':' a lot. I know it is used for loops or if statements but i have seen it in variable assignment also. Wanted to know the general use of it?
8 Answers
+ 3
You can leave a type annotation with an assignment. Instead of...
x = 'Hello'
... you'd write...
x: str = 'Hello'
It doesn't enforce that x refers to a string, so I am not sure why even do it, but anyway, you can do it. ;-)
+ 1
It's used instead of { } in most of the cases
+ 1
There are two use of :
One already specified above by Alvaro 1234
Another it is used in dictionary {1:3,4:5} to specify key value pair
There is no relation between both uses
+ 1
: is also a slicing operator for lists. For example to get all the elements of a list in reverse order, you can use
mylist[::-1]
+ 1
HonFu thanks now I learned something new too :)
I have only ever seen type annotation in function declarations. And the usefulness is the same as a comment or docstring: if someone else wants to use your function, they get some guidance what sort of parameter the function expects...
+ 1
It often says that the code-block of the following indent level belongs to a certain statement.
One-line code-blocks do not necessarily need indentation. "if expression: statements".
Lambda function definitions only support one-line code-blocks.
Ofcourse dictionaries use ":", but I think it is independent from the other purposes.
If you use [:] you launch a slicing operator. (Only ordered iterables support slicing.) list[x:y:z] calls list.__getitem__ somehow, but not sure how.
0
Pulkit Kamboj can you explain the dictionary use you wrote?
0
The dictionary is a collection that contains pairs of data: one key and one value. The semicolon separates the key from value when you define the dict. An example to keep track of test scores:
scores = {'Tom' : 94, 'Jerry' : 42}
print(scores['Tom'])