Tuple or list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Tuple or list

I don't know why python has tuples and lists, when should I use tuples?

24th Sep 2018, 8:43 PM
Enzo Falcon
Enzo Falcon - avatar
5 Answers
+ 3
You can't change a tuple which might be useful (if you want things to stay constant). Tuples are also like mini-classes (or objects). Python has named tuples which show that really well, check this: Address = namedtuple('Address', ['name', 'city']) a = Address(name = 'Frank', city = 'Sydney') print(a.name) print(a[0]) Unnamed tuples like ('Frank', 'Sydney') are the same, just that you don't bother writing down the names. So Tuples are for data with a fixed "layout". You can use a list for almost anything you can use a tuple for and the other way around, but that's not really the point :)
24th Sep 2018, 9:50 PM
Schindlabua
Schindlabua - avatar
+ 2
Usually you will use a list for an *unknown* number of elements for a *single* type. So maybe all integers, all strings, etc. A tuple is for a *known* number of elements for *many* types. So maybe a 3-tuple with two integers and a string. In python you can mix data any way you want but that's the general guidelines. Another important thing is that lists are mutable, that means, you can add or remove or change stuff in a list. Tuples are immutable, so everytime you change something, a new tuple will be created and everything will be copied over (even though you might not notice that when programming). EDIT: For example if you are writing an address book where each entry is a name and a number, you would use a list of tuples (the tuples containing two strings each). Each entry has a fixed format, so you use a tuple, but there can be a lot of entries, so you use a list.
24th Sep 2018, 8:52 PM
Schindlabua
Schindlabua - avatar
+ 2
not sure about this. I used an other programing language ,MDL, that had lists (vectors in MDL) and tuples. tuples were stored on the return stack and vectors were stored in a GCed heap. is this also ture in python? I think the biggest differnce in python between list and tuples is that once the tuple is created, its contents can't be changed. List can be changed both contents and length.
28th Sep 2018, 7:14 AM
Rick Shiffman
Rick Shiffman - avatar
0
Is there an advantage of using a tuple instead of a list?
24th Sep 2018, 9:08 PM
Enzo Falcon
Enzo Falcon - avatar
0
Wow, I've been doing a lot of things wrong, thanks for the help!
25th Sep 2018, 4:05 AM
Enzo Falcon
Enzo Falcon - avatar