So I have an assignment that is due later tonight and I’m stuck on this one definition. What I have is a list of random terms:
['i', 'am', 'a', 'brown', 'cow']
And what I want to do with this list is associate each term to a value/term:
[['i', ['term']], ['am', ['term']], ['a', ['term']], ['brown', ['term']], ['cow', ['term']]]
My thoughts on how to get started on this was to use a for loop and append the term after each key term and somehow try to separate each pair.
If you are a beginner in Python, the most obvious option probably would be simple loop approach:
After this you can access your elements like this:
Of course, this is not the best way to do this. As other have already said, you should take a look at list comprehension and builtin
zip()function. I will try to write some examples of code using list comprehension andzip()function, but it is still highly recommended to read the official documentation.You should note that list comprehension always gives you a list as a result, so the best thing you can get is what you have demonstrated in your question. Here is a small example:
This will give you exactly the same you have written in your question. In case you want to get a dict (as in our first example), you might want to modify this code slightly:
And again you have:
Now, you probably want to assign different terms to different elements of your list.
Let’s say you have two lists of the same length, one with elements, the other with terms:
This is where
zip()function helps. If you pass itlstandtermsas arguments, it will give you a list of tuples (just as in ourresvariable a few lines before):And now you can again use
dictto create a new dictionary: