#๐Ÿ”’ constructors vs literals

39 messages ยท Page 1 of 1 (latest)

magic bloomBOT
#

@south crown

Python help channel opened

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.

tropic skiff
#

the constructors allow you to make objects from other objects

#

!e

print(list("abc"))
magic bloomBOT
tropic skiff
#

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))
magic bloomBOT
tropic skiff
#

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))
magic bloomBOT
tropic skiff
#

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)
magic bloomBOT
tropic skiff
#

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)
magic bloomBOT
tropic skiff
#

demonstration of using constructors

magic bloomBOT
#
Python help channel closed using Discord native close action

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.