+ 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?

19th Jun 2019, 11:10 AM
DEVANSH BANSAL
DEVANSH BANSAL - avatar
8 ответов
+ 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. ;-)
19th Jun 2019, 11:57 AM
HonFu
HonFu - avatar
+ 1
It's used instead of { } in most of the cases
19th Jun 2019, 11:30 AM
alvaro.pkg.tar.zst
alvaro.pkg.tar.zst - avatar
+ 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
19th Jun 2019, 11:39 AM
Pulkit Kamboj
Pulkit Kamboj - avatar
+ 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]
19th Jun 2019, 11:51 AM
Tibor Santa
Tibor Santa - avatar
+ 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...
19th Jun 2019, 12:41 PM
Tibor Santa
Tibor Santa - avatar
+ 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.
19th Jun 2019, 6:36 PM
Seb TheS
Seb TheS - avatar
0
Pulkit Kamboj can you explain the dictionary use you wrote?
19th Jun 2019, 12:11 PM
DEVANSH BANSAL
DEVANSH BANSAL - avatar
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'])
19th Jun 2019, 12:24 PM
Tibor Santa
Tibor Santa - avatar