+ 1

Related to Tuple and list

I understand the function of tuple and list, but how does one create a tuple and list in a way that computer doesn't misunderstands it for each other?

3rd Jun 2024, 4:26 PM
Chris
Chris - avatar
5 Respostas
+ 8
When it comes to iterables (e.g. string, tuple, list, set, dict), the symbol used for creating new object distinctiate the object type. The computer (Python interpreter) will clearly understand what type an object really is, as long as you define the object in correct syntactics, as in using the proper symbol. a_string = 'hello world' Single or double quotes tells Python that it is a string a_tuple = ( 'one' , 'two' , 'three' ) Parentheses with plain values, tells Python that it is a tuple a_list = [ 'one' , 'two' , 'three' ] Square brackets with plain values, tells Python that it is a list a_set = { 'one' , 'two' , 'three' } Curly brackets with plain values, tells Python that it is a set a_dict = { 'one' : 1 , 'two' : 2 , 'three' : 3 } Curly brackets with pairs of key and value, tells Python that it is a dict IIRC there are examples covering this subject in the course, I'd look back into it if I were you :)
3rd Jun 2024, 6:14 PM
Ipang
+ 9
In Python, the tuple is enclosed by normal parentheses ( ) and the list is enclosed by square brackets [ ]
3rd Jun 2024, 5:59 PM
Tibor Santa
Tibor Santa - avatar
+ 9
since tuple is an immutable data type, the generation of a tuple from an input can not be done in the way that we can use to create a list. tuple has no method to add / append elements. there are several ways to create tuples, one of them is to use a generator expression and convert this to a tuple. the same can be done to create a list. https://sololearn.com/compiler-playground/cKrCfvYmM5Em/?ref=app
3rd Jun 2024, 6:36 PM
Lothar
Lothar - avatar
+ 7
Chris Always be sure to tag the programming language you are referencing 😉
3rd Jun 2024, 5:56 PM
Keith
Keith - avatar
+ 6
Chris The syntax of tuple and list are different, so the interpreter itself identifies which is tuple and which is list. You don't have to differentiate them.
3rd Jun 2024, 4:58 PM
Ayush Singh
Ayush Singh - avatar