difference between [] and list() in python3 - list

I thought that [] and list() were two equal ways to create a list. But if you want a list with dictionnary keys,
var = [a_dict.keys()]
doesn't work since type(var) is [dict_keys], correct syntax is :
var = list(a_dict.keys())
I couldn't find an good explanation on this behaviour. Do you have one ?

TL;DR:
list() is the same as []
list(obj) is not the same as [obj]
a_dict.keys() is a dictionary view object, it returns an object which can be iterated to yield the keys of a_dict. So this line:
[a_dict.keys()]
is saying in python "I'm making a list with one element in it" and that one element is the dict keys iterator. It's a list literal in the syntax.
Now this line:
list(a_dict.keys())
is a call to the list builtin function. This function list attempts to iterate the argument and produce a list. It's a function call in the grammar.
The equivalent list literal (actually list comprehension) would be instead:
[key for key in a_dict.keys()]
Finally, note that dictionary objects iterate by keys anyway,
list(a_dict.keys()) would usually be written more simply as as list(a_dict) instead.
Hope this helps.

[a_dict.keys()]
This one puts a single element in the list. Just as if you were to write [1]. In this case that one element is going to be a list.
list(a_dict.keys())
The constructor accepts a sequence and will add all elements of the sequence to the container.

Related

How do I output a specific item in a list when inputted a number that corresponds to that item? [Indexing?]

Number,IceCream
1,Chocolate
2,Vanilla
3,Mixed
Say if I
Number = input("Flavor?:")
I know that I need to index [0] because the numbers are on the first column. I also know that I will need to use .split(",") to remove the commas and to create a list.
Some assistance would be greatly appreciated!
It's confusing whether you plan to include integers in the list with the strings or not
Method 1: including integers with strings(flavor), create a list of tuples
icecream=[(1,'choc'),(2,'mix'),(3,'blueberry')]
print(icecream[0][1])
print(icecream[2][1])
Note: tuples are immutable
Method 2: I believe the best way to do this would be to use a dictionary instead of list. As dictionary has (Key, value) pairs, you could assign key(integer) to values(flavor), which then would make it easy accessing items just by keys(integers in your case) ex.
Ice_cream_flavors={1:"chocolate", 2:"vanilla", 3:"mixed"} #dictionary
to access values, you could use methods available in dictionary use get(), items()
Note: items() returns a tuple for each key,value pair.
ex.
Ice_cream_flavors={1:"chocolate", 2:"vanilla", 3:"mixed"}
new=Ice_cream_flavors.items()
for k,v in new:
if input==k:
print(v)

Removes braces from variable

I am comparing two list:
gp_yu = set(agencys_sp2).intersection(gp_list_t)
the output is in braces like this {900}. What can i do to remove the braces
You can obtain an element from an iterable iterable (a set is an iterable, but lists, dictionaries, etc. are iterables as well) with:
element = next(iter(iterable))
In case the iterable contains two or more elements, it will return the first element (a set has no really a "first" element in the sense that the order can very over time, but it will return an element).
In case the iterable contains no elements at all (an empty set, list, tuple, dictionary, etc.), then it will raise a StopIteration error. You can however let the expression return a default value with:
element = next(iter(iterable), default)
So in case iterable contains one or more elements, the "first" element is returned, in case it is empty, it will return default.
Probably you mean some like how to get your set as a string, so just use join function.
Some like this ', '.join(gp_yu).
Check this topic for more information:
Python: how to join entries in a set into one string?

Iterate over an existing map against a list of tuples scala

I have a list of tuples that I must change the values for in a map that contains those tuples. So if I have a list such as List((0,2), (0,3)) with a map that looks like this: Map((0,2) => List(1,2,3), (0,3) => List(1,2)), I need to access the matching map tuples with the tuples listed in the list, then remove a number from the mapping.
So in the example above, if I wanted to remove 2 from the mapping, I would get Map((0,2) => List(1,3), (0,3) => List(1)).
Design wise, I was thinking of pattern matching the map, but I've read some answers that said that may not be the best way. The tough part for me is that it has to be immutable, so I was thinking of pattern matching the list, getting the map value, change the value, then recreate the map and recursively call the function again. What do you think of this implementation?
This could be a way to remove 2 from your Map:
val newMap = oldMap.mapValues(list => list.filter(_ != 2))
Or more generally:
def filterInMap(element: Int, oldMap: Map[(Int,Int),List[Int]]) =
oldMap.mapValues(list => list.filter(_ != element))
This way there's no need to mutate anything at all. mapValues transforms just the values of your Map and returns a copy of the original without mutating it at all. filter then gets the job done by only allowing elements that don't match the element we would like to remove.
Bonus: even more generally:
def filterInMap[A](element: A, oldMap: Map[(A,A),List[A]]) =
oldMap.mapValues(list => list.filter(_ != element))

How to check and change the value of a list?

I would like to check all list values in a list and change them if necessary.
p.e.
I want to check the next lists if there are values higher or lower then the next values:
min-value = 6
max-value = 22
mylist = ['4-8','25','16-19','21-32']
if one of the list values is below the min-value or higher then the max-value, the list values must be changed to the min-value and max-value. p.e. in example, the new list must be:
mylist = ['6-8','22','16-19','21-22']
if the entire value of the list item is below the min-value or higher then the max-value the list item can be removed.
How can I check my list values and change them?
There are two approaches. In the procedural one, you iterate over the list items and modify or skip the element:
let newlist = []
for element in mylist
" Parse element.
if ! OutsideBounds(element)
call add(newlist, AdjustBounds(element))
endif
endfor
In the functional programming approach, you use the built-in map() to modify elements (i.e. adjust the bounds), but that one cannot remove elements. So just empty those elements and then do a second pass with filter() to remove them. Note that both functions modify the original lists, so use copy() if you need to keep the original.
call filter(map(mylist, 'AdjustBounds(v:val)'), '! OutsideBounds(v:val)')
I hope I don't need to tell you how to write the AdjustBounds() and OutsideBounds() functions...

Prolog Insert list as element into another List

In my program my P = [0,1,2] I want to store it into another LIST, because P will keep changing in a loop so I want to store P into a LIST, so my LIST will be like below :
eg.
LIST = [[0,1,2],[3,4,5],[6,7,8]]
create_list([],[]).
create_list(G, [H|G]).
This is what I did, create_list(P,LIST). I not sure how to do it as it keep return me no. But I am pretty sure I can get different P because I am able to print them out each time P changed.
You need to create a predicate that receives the item (list in this case) you want to append to another input list, and this would give you a new list with the which has all the items of your input list plus the new item.
So, it would be something like:
create_list(Item, List, [Item|List]).
Initially the input List would be an empty list ([]), so you might call it
create_list([0,1,2], [], List1),
create_list([3,4,5], List1, List2),
create_list([6,7,8], List2, List).
This will result in List instantiated with [[0,1,2],[3,4,5],[6,7,8]]