#๐ constructors vs literals
39 messages ยท Page 1 of 1 (latest)
@south crown
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
the constructors allow you to make objects from other objects
!e
print(list("abc"))
:white_check_mark: Your 3.13 eval job has completed with return code 0.
['a', 'b', 'c']
tho, the way it works with list and dict is a bit different than with string
string needs the dunder becasue it can so varied the way that you would want to make something into a string
!e
pairs = [
("a", 1),
("b", 2),
]
print(dict(pairs))
:white_check_mark: Your 3.13 eval job has completed with return code 0.
{'a': 1, 'b': 2}
also, empty sets cannot be made without doing set()
because {} means empty dict
do tell me tho, how would you make a list with 1 2 3 in it without using [], and instead using list()?
so there's another difference
list and dict don't use specific dunder methods to their classes
instead, they use other methods
for example, __iter__
which is what makes things such that you can loop through them
the problem with list() is that you need to give it some other value
so like, you could do list([1, 2, 3]), but that's redundant
there is __dict__, but it has a different meaning
yep
yes
there's another way you can use the dict constructor, which is keyword arguments
!e
print(dict(a=1, b=2))
:white_check_mark: Your 3.13 eval job has completed with return code 0.
{'a': 1, 'b': 2}
you can also pass a dict-like object to dict, and it will make a new dict out of it
I think it needs .keys() and .__getitem__()
so if you pass a dict to the dict constructor it will make a shallow copy
same with list and list
!e
a = [1, 2, 3]
b = list(a)
print(a is b)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
False
yeah
same like doing your_list.copy() in this case
or your_list[:]
check this out
!e
string = "abcbsahbcasjhbvqawugvcasicbash"
print(string)
unique = set(string)
print(unique)
indexable = list(unique)
print(indexable)
indexable[:5] = "hello"
print(indexable)
:white_check_mark: Your 3.13 eval job has completed with return code 0.
001 | abcbsahbcasjhbvqawugvcasicbash
002 | {'b', 'h', 'j', 'i', 'v', 'w', 'g', 's', 'q', 'a', 'u', 'c'}
003 | ['b', 'h', 'j', 'i', 'v', 'w', 'g', 's', 'q', 'a', 'u', 'c']
004 | ['h', 'e', 'l', 'l', 'o', 'w', 'g', 's', 'q', 'a', 'u', 'c']
demonstration of using constructors
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.