r/learnpython • u/coffeedrinker1994 • Jul 03 '20
In the most basic terms, please explain when you would use tuples,lists,dictionaries, or sets.
Hello, I have been rereading and seeking different definitions and watching different videos explaining python, but I cannot understand what the difference is between tuples,lists, dictionaries, and sets other than some you use {} [] or (). When would you use these? What are the practical differences? please explain in the absolute simplest caveman terms
Edit: Thank you all for your generosity of knowledge. I have learned alot from reading all the comments and answers.
4
u/AusIV Jul 03 '20
Tuples: I seldom use them outside of certain syntactic use cases, like if I need a function to return multiple values. For example:
def x():
return 1, 2, 3
a, b, c = x()makes use of tuples, but I never assigned a tuple anywhere. Tuples can be useful when you need a collection of things that can't change, but in practice I still usually use lists outside of ephemeral syntactic use cases like the one above.
List: Any time I need an ordered collection of things, I use a list.
Dictionary: Map keys to values efficiently. You can't get this from any of the other data structures.
Sets: Sets are most valuable for figuring out of one item belongs to a group of items (membership testing). Suppose I have a 10,000 word essay, and I have a bunch of words that I want to check to see if they appear in the essay. If I do:
for word in wordList:
if word in essay:
# do whateverIt has to scan the entire essay for each word to see if it's present. If I do:
essayWordSet = set(essay.split()) # Pretend like capitalization and punctuation aren't a concern
for word in wordList:
if word in essayWordSet:
# do whateverNow instead of having to check every word in wordList against every word in essay, we can look things up in the set much more quickly (because of how the set organizes the data internally). If there are 10,000 words in the essay, this case is 10,000 times faster (ish).
But sets also let you do other things. For example, you could just do:
set(essay.split()) & set(wordList)To get a list of the words that are in both the essay and the wordList.
The limitation of sets, and why you don't always use them in place of lists are primarily that they aren't ordered and they can't have duplicates. If order matters or your dataset might have multiple copies of an item, you're better off using a list.
3
u/fedeb95 Jul 03 '20
Aside from tuples, the other use cases become clear when you examine their time and space performance and characteristics. For instance, stets only store each different element once. So let's say you want to have a collection without duplicates, you use a set. A dictionary (or hash map) has a key-value structure, and is very fast in retrieving an element from it. So if you need that to be fast, go for a dictionary. Other probably explained use cases more in depth, but I suggest you to learn some more data structure theory to really grasp why and when to use what
3
Jul 03 '20
Tuples: immutable, have order, not sortable.
Tuples are for where position has meaning. And by meaning, i'm not talking about sorting.
In a class room, the first item is teacher, second item is number of students, third item is class subject, fourth item is grade level.
List: mutable, have order, sortable.
Lists are for when being able to sort is important. For example, the list would be names of students in order of academic performance. This will change, and require resorting.
Lists can be added to and removed from, unlike tuples. But that's not their "key feature." The key feature is it that they can be sorted and resorted, that is position is likely to change.
Sets: mutable, no order, no sorting.
Sets have no order, but that's not the point. The point is that you can treat them arithmetically. `active_users = all_users - expired_users`.
3
u/bbt133t Jul 03 '20
You wanted simple so 4 lines is what you get, why and when to use:
Lists - mutable and allow duplicate elements
Tuples - same as Lists but immutable
Sets - same as lists but do not allow duplicate elements
Dictionaries - a combination of keys behaving like a set and values behaving like a list
6
u/Cwlrs Jul 03 '20 edited Jul 03 '20
Tuples: Immutable (can't be changed once assigned information). Use cases: For some libraries and functions, the input type of some arguments must be a tuple. Even thinking now, I can't think of the reason why they needed it to be a tuple as opposed to a list, but this is my personal day to day reason for using a tuple. I specifically remember having to use the syntax (var,) with a randomly placed comma in a tuple of length 1 to make it a tuple type.
Lists: Mutable (can have items added, removed, order changed, etc) and are the most versatile, and easy to use data type. These are useful for storing many unique and non unique values, where the order of them may or may not be important to you later, and there is no other associated data with a single set of values. Or if there is, consider using a list of lists. Lists are my main weapon of choice for many scenarios. Pros: most versatile, and can be used in almost all situations. Cons: will likely be slower than the following data structures for certain tasks regarding unique values, and for finding data stored in a data structure.
Dictionaries: Mutable, hash tables. These are excellent for storing data (value) against a certain key. e.g. counting the number of wins and appearances of a certain thing, like highest dice roll, then you can do dict_wins['5']/dict_apps['5'] where you have run many simulations of the dice roll, and constantly added to the dict[value] by using +=1 for example. Dicts are also very fast at accessing a specific key due to the nature of the hash table. e.g. if you search for dict_wins['5'], it's very fast, whereas searching a huge list for the first '5' value or the count of '5' is much longer. I mainly use dictionaries to count rolling totals or values against a certain type of key value, some other variable maybe like a dice roll, or a string description of something. They are useful for string based data too, and look and feel like .json file, commonly used for configuation. So you can read a .json file and parse the data into a dictionary. Useful for making your own config files too, especially compared to a list, where you can do dict_config['login_pw'] - and then add new information to the dict, and you won't mess up the structure, as opposed to if you have list_config[2] and added a new value at the start of the list, you will now be referring to the wrong data. The dictionary structure is better than the list here.
Sets: Similar to dictionaries, but are mainly used in coding games to have the fastest code. They are mainly used to test for uniqueness of values in a dataset. Using set_values.add(value) adds a value to a set, and if the value already exists in the set, nothing is added. Only new unique values are added. You can find the length of the set to find the number of unique values that have appeared in your project, you can iterate over all values in the set like, for i in set: print(i). Which you can't do for a dictionary. However it will be an unordered for loop through the set, due to the nature of the hash function. You cannot order a set. Main benefits are the insane speed for testing uniqueness of a dataset, drawbacks are it is very inflexible and can't achieve much else from my experience.
3
u/ianepperson Jul 03 '20
You absolutely can iterate over a dictionary. (for i in dictionary definitely works. ) In fact, you have three options for doing that.
For i in dictionary - walks through just the keys. For i in dictionary.keys() does the same, but a bit more explicit.
For i in dictionary.values() walks you through the values stored in the dictionary. I find this less useful, but it's good to know about.
The most useful is "dictionary.items()" which gives you both in a tuple. For key, value in dictionary.items() works well and is really useful.
2
u/Cwlrs Jul 03 '20
Oh cool, I literally didn't know that! Thought that made my programs crash back in the day. I thought I would have tried it by now.
2
u/COMPROTKS-8881 Jul 03 '20
HI IAM A BEGINNER,
But I know-how list and tuples vary it is quite simple
*LIST => A list contains millions of values like the alphabet , numeric (0-9) and each element is enclosed by square brackets.For instance [1,'animal','car','bike'].These are mutable(changeable) we can change,add,remove.
*TUPLE=> Tuple is immutable. Once we created a tuple we can't change it
7
Jul 03 '20 edited Jul 03 '20
[removed] — view removed comment
1
u/coffeedrinker1994 Jul 03 '20
Very grateful for your answer, this sort of thing always makes sense to me when somebody explains using really simple examples, such as your fruit example.
1
u/blazingshadow1 Jul 03 '20
Also I would like to add just one thing. One main difference when it comes to sets it that they are extremely efficient at checking membership of a value. For example if you want to know if 3 is there in a list of 100 items and if you wanna know if 3 is there in a set of 100 items. It will take longer time in list. In set the check for membership takes the same time regardless of it's size.
2
u/jwink3101 Jul 03 '20
I assume you meant to change the second "100" to something like "1000".
To OP: This is one of the many great uses for sets!
Also, pro-tip, if for some reason you are still support python 2:
First of all, stop supporting python 2! Second of all, if you're checking for membership in a dictionay do:
mykey in mydictand not
mykey in mydict.keys()In python2, the latter first makes a list and the checks the membership in the list. The former uses set-like opperations.
Quick testing is that the former is also faster in python 3.7 but not by much.
6
u/gardyna Jul 03 '20
Great answer, but you did miss one of the most important aspect of sets (and IMO the most useful one). sets do not contain duplicates. one way to check if a list contains duplicates is converting it to a set and seeing if the length is the same
myList = [1, 2, 3, 4, 4, 5,...] containsDuplicates = (len(myList) == len(set(myList)))
364
u/ka-splam Jul 03 '20 edited Jul 03 '20
They are all ways of storing and accessing data, so very similar in that sense. What's different is the things they focus on, and the things they do faster or slower.
Lists are the simple way to hold many things. They can hold
[1,2,3,4,3,2,1], almost as much as you like, you can add more things, remove things, change things. And you can pull things out by position or one at a time from beginning to end, or from a few positions at once. Good place to hold all kinds of things - lines of text from a file, user accounts, websites to scrape, filenames from a folder, whatever you're working with will probably go in a list at some point. Almost whatever, whenever. The default thing to use.Sets are like the mathematical sets - they can't contain duplicates, they would see that list above as
{1,2,3,4}only the unique members. This is good for doing math-set things like Venn diagrams show circles overlapping - "things which are in this set, AND in that set", or "things in that set and NOT in this set". Union, intersection. They tend to have a fast check for "is something in the set?", faster than you can check if something is in a list. If you're doing that a lot, it makes sense. They're a bit specialised.Tuples are a more limited list, they can't grow or shrink, or have items changed or replaced, which makes them less useful, but they have less overhead so they run a bit faster. Good if you're doing something like pairs of items and you know there will always be two, or dealing with images and you have
(Red, Green, Blue)colours going together, say. Usually used without paying much attention to it in things likefor index, value in enumerate(x):there's a tuple in there around the comma, no()needed.Dictionaries are wildly different, they're a way to store things tagged by a name (a key). Then you can lookup the tag and get the things back. E.g. lookup user ID, get email address back. They are extremely quick at finding things by name, and mapping key -> value is very useful in a ton of programming situations.
one example use, web scraping:
you make a list of website addresses to scrape
['http://example.com', 'http://google.com']as you scrape them and get web page content back, you need somewhere to put that
you make a dictionary of
{address: content}lookups.{'http://example.com' : "<EXAMPLE HTML...", 'http://google.com': "<GOOGLE HTML..."}.now you can go through the web addresses, lookup their name in the dictionary and pull out their content when you need to work on it.