From October 17-20 in Las Vegas, JavaOne will be jam-packed with hundreds of valuable and actionable sessions directly from the experts. You’ll find learning sessions, tutorials, hands-on labs, lightning talks, panels, an unconference, and birds-of-a-feather sessions, covering a variety of topics from the Core Java Platform, to Cloud Development, AI/ML, Security and Manageability, and more.
This method uses List Comprehension to apply a mathematical operation to each element and return the result.
prime_nums = [2, 3, 5, 7, 11]
mult_result = [x * 2 for x in prime_nums]
print(mult_result)
Above declares the first (5) Prime Numbers and saves this List to prime_nums. Next, List Comprehension loops through each element and applies the multiplication operation to each. The output saves to mult_result and is output to the terminal.
[4, 6, 10, 14, 22]
Method 2: Use Pandas tolist()
This method requires an additional library to be imported, Pandas, to use the tolist() function.
Above, imports the Pandas Library. Click here if this requires installation. Then, the first (5) Prime Numbers are declared and saved to prime_nums.
Next, prime_nums is passed as an argument to the pd.Series() function and returns mult_result. The output of mult_result at this point is shown below.
0 2 1 3 2 5 3 7 4 11 dtype: int64
Now, we need to convert this output to a list (tolist()) and apply the multiplication operation to each element. The results save to mult_result and are output to the terminal.
[4, 6, 10, 14, 22]
Method 3: Use map and lambda Functions
This method wraps the map(), and lambda functions inside a Python List and calculates the results.
Above declares the first (5) Prime Numbers and saves them to prime_nums. The next line does the following:
The map() function is passed the lambda() function as an argument (map(lambda x: x*2, prime_nums)).
The lambda performs the multiplication operation to each element of prime_nums and saves it to map() as an object similar to below. <map object at 0x000001DC99CBBBB0>
Above, imports the NumPy Library. Click here if this requires installation. Then the first (5) Prime Numbers are declared and saved to prime_nums.
Next, prime_nums is passed as an argument to np.array() where the multiplication operation is applied to each element. Then, this is converted to a List, saved to the_result and output to the terminal.
[4, 6, 10, 14, 22]
Method 5: Use Slicing
This method uses Python’s infamous Slicing! No overhead, and a very pythonic way to resolve the issue.
prime_nums = [2, 3, 5, 7, 11]
prime_nums[:] = [x * 2 for x in prime_nums]
print(prime_nums)
Above declares the first (5) Prime Numbers and saves them to prime_nums.
Then slicing is applied and used in conjunction with List Comprehension to apply the multiplication operation to each element. The results save back to prime_nums and are output to the terminal.
[4, 6, 10, 14, 22]
A Finxter Favorite!
Summary
These methods of multiplying list elements by a number should give you enough information to select the best one for your coding requirements.
Good Luck & Happy Coding!
Programmer Humor
Programmer 1: We have a problem Programmer 2: Let’s use RegEx! Programmer 1: Now we have two problems
The GameCreators Bundle | Save 98% OFF over $300-worth of content
[www.indiegala.com] Become a gamedev on your own & create your dream video game with the help of GameGuru, AppGameKit & a vast selection of asset packs. From Fantasy to Sci-Fi, from buildings to gardens, a mega giant array of options & tools are available for you to choose from.
The games are free to keep until July 21st 2022 - 15:00 UTC.
Next week's freebie: Shop Titans Tannenburg
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
Klonoa Phantasy Reverie Series brings back "Klonoa: Door to Phantomile" and "Klonoa 2: Lunatea's Veil" remastered in one collection to fans new and old. Get ready to set off on an adventure to save the world. Released initially in 1997 by Namco, Klonoa is a side-scrolling platformer featuring a colorful character roster and vibrant game world, it's up to you as Klonoa to embark on a journey to save Phantomile. For the franchise's momentous twenty-fifth birthday, Klonoa: Door to Phantomile and Klonoa 2: Lunatea's Veil are receiving the remaster treatment in a two-in-one set—titled KLONOA Phantasy Reverie Series slated to hit the Nintendo Switch™, PlayStation®5, PlayStation®4, Xbox Series X|S, Xbox One, and Steam. The graphics have received an elegant revamp while Klonoa's beloved world and classic gameplay have been faithfully preserved. The remaster also features an adjustable difficulty level, allowing franchise newcomers to delve right into the action, and long-time fans to get reacquainted with ease.
Posted by: xSicKxBot - 07-15-2022, 12:22 AM - Forum: Lounge
- No Replies
Buy $100 Xbox Gift Card, Get A $20 Target Gift Card As A Bonus
The only thing better than getting money is getting free money, which is the offer that Target currently has available. The deal itself is simple as the purchase of a $100 Game and Grub gift card will earn you a free $20 Target gift card to spend at the retail chain. That statement of free money then is technically correct, which is the best kind of correct.
The Game and Grub gift card can be redeemed on Xbox, Grubhub, Domino's Pizza, Dave & Busters, and at Buffalo Wild Wings. Just don't try to insert a pizza into your Xbox or attempt to eat a Halo Infinite disc, as that will be a waste of $100.
The gift card has no expiration date according to the fine print and once purchased it'll be emailed to you so that it can be redeemed online at participating brands. While Prime Day ended yesterday, you can still check out our Xbox roundup on the best deals for that games console.
Posted by: xSicKxBot - 07-14-2022, 03:51 AM - Forum: Python
- No Replies
How to Fix TypeError: unhashable type: ‘list’
5/5 – (2 votes)
The TypeError: unhashable type: 'list' usually occurs when you try to use a list object as a set element or dictionary key and Python internally passes the unhashable list into the hash() function. But as lists are mutable objects, they do not have a fixed hash value. The easiest way to fix this error is to use a hashable tuple instead of a non-hashable list as a dictionary key or set element.
We’ll show how this is done in the remaining article. The last method is a unique way to still use lists in sets or dictionary keys that you likely won’t find anywhere else, so keep reading and learn something new!
Problem Formulation and Explanation
Question: How to fix the TypeError: unhashable type: 'list' in your Python script?
As you’ve seen in the previous two code snippets, the TypeError: unhashable type: 'list' usually occurs when you try to use a list object as a set element or dictionary key.
But let’s dive deeper to find the real reason for the error:
Minimal Reproducible Error Example: Lists are mutable objects so they do not have a fixed hash value. In fact, the error can be reproduced most easily when calling hash(lst) on a list object lst.
This is shown in the following minimal example that causes the error:
hash([1, 2, 3])
The output is the error message:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 1, in <module> hash([1, 2, 3])
TypeError: unhashable type: 'list'
Because you cannot successfully pass a list into the hash() function, you cannot directly use lists as set elements or dictionary keys.
But let’s dive into some solutions to this problem!
Method 1: Use Tuple Instead of List as Dictionary Key
The easiest way to fix the TypeError: unhashable type: 'list' is to use a hashable tuple instead of a non-hashable list as a dictionary key. For example, whereas d[my_list] will raise the error, you can simply use d[tuple(my_list)] to fix the error.
The error may also occur when you try to use a list as a set element. Next, you’ll learn what to do in that case:
Method 2: Use Tuple Instead of List as Set Element
To fix the TypeError: unhashable type: 'list' when trying to use a list as a set element is to use a hashable tuple instead of a non-hashable list. For example, whereas set.add([1, 2]) will raise the error, you can simply use set.add((1, 2)) or set.add(tuple([1, 2])) to fix the error.
Here’s a minimal example:
my_set = set() # Error: my_set.add([1, 2]) # This is how to resolve the error:
my_set.add((1, 2))
# Or: my_set.add(tuple([1, 2])) print(my_set)
# {(1, 2)}
If you want to convert a list of lists to a set, you can check out my detailed tutorial on the Finxter blog:
Method 3: Use String Representation of List as Set Element or Dict Key
To fix the TypeError: unhashable type: 'list', you can also use a string representation of the list obtained with str(my_list) as a set element or dictionary key. Strings are hashable and immutable, so Python won’t raise the error when using this approach.
Here’s an example:
my_list = [1, 2, 3] # 1. Use str repr of list as dict key:
d = {}
d[str(my_list)] = 'hello Finxters' # 2. Use str repr of list as set element:
s = set()
s.add(str(my_list))
In both cases, we used the string representation of the list instead of the list itself. The string is immutable and hashable and it fixes the error.
But what if you really need a mutable set or dictionary key? Well, you shouldn’t but you can by using this approach:
Method 4: Create Hashable Wrapper List Class
You can still use a mutable list as a dictionary key, set element, or argument of the hash() function by defining a wrapper class, say HackedList, that overrides the __hash__()dunder method.
Python’s built-inhash(object) function takes one object as an argument and returns its hash value as an integer. You can view this hash value as a unique fingerprint of this object.
The Python __hash__() method implements the built-in hash() function.
Here’s the minimal code example that creates a wrapper class HackedList that overrides the __hash__() dunder method so you can use an instance of HackedList as a dictionary key, set element, or just as input to the hash() function:
my_list = [1, 2, 3] class HackedList: def __init__(self, lst): self.lst = lst def __hash__(self): return len(self.lst) my_hacked_list = HackedList(my_list) # 1. Pass hacked list into hash() function:
print(hash(my_hacked_list)) # Output: 3 # 2. Use hacked list as dictionary key:
d = dict()
d[my_hacked_list] = 'hello Finxters' # 3: Use hacked list as set element:
s = set()
s.add(my_hacked_list)
Here’s the content of the dictionary and set defined previously:
{<__main__.HackedList object at 0x0000016CFB0BDFA0>: 'hello Finxters'}
{<__main__.HackedList object at 0x0000016CFB0BDFA0>}
If you want to fix the ugly output, you can additionally define the __str__() and __repr__() magic methods like so:
my_list = [1, 2, 3] class HackedList: def __init__(self, lst): self.lst = lst def __hash__(self): return len(self.lst) def __str__(self): return str(self.lst) def __repr__(self): return str(self.lst) my_hacked_list = HackedList(my_list) # 1. Pass hacked list into hash() function:
print(hash(my_hacked_list)) # Output: 3 # 2. Use hacked list as dictionary key:
d = dict()
d[my_hacked_list] = 'hello Finxters' # 3: Use hacked list as set element:
s = set()
s.add(my_hacked_list) print(d)
print(s)
Beautiful output:
{[1, 2, 3]: 'hello Finxters'}
{[1, 2, 3]}
Summary
The five most Pythonic ways to convert a list of lists to a set in Python are:
[www.indiegala.com] Tackle the summer heat with an even hotter Match3 treat! A selection of casual match3 puzzle games with distinctive elements are waiting to be solved: Gaslamp Cases 2, 100 Days without delays, Funny Pets, Halloween Trouble 2, Catherine Ragnor and the Legend of the Flying Dutchman, Rorys Restaurant Deluxe, Suddenly Meow, Save the Planet, The lost Labyrinth
What would you do if you woke up locked in a dark room, with your hands covered in blood? Play as Luca, and endure the brute torture of MADiSON, a demon that has forced him to continue a gory ritual started decades ago, making him commit abominable acts. Will you be able to finish this sinister ceremony?
Posted by: xSicKxBot - 07-14-2022, 03:51 AM - Forum: Lounge
- No Replies
Klonoa Phantasy Reverie Series Already On Sale For A Nice Discount
Klonoa Phantasy Reverie Series has only been out less than a week, but you can already grab it at a discount from Fanatical. The PC games retailer is selling the remastered double-pack of the PS1-era platformers for $34, a tidy discount from its usual price of $40.
Klonoa first appeared in Klonoa: Door to Phantomile in 1997, followed by Klonoa 2: Lunatea's Veil in 2001. This collection marks the 25th anniversary of the series by compiling them both with updated graphics, new difficulty settings to make the games more approachable, and costume options with DLC. The base compilation game includes a Moo costume set.
This deal is only available for a limited time, so the sale price will expire at approximately 7 PM PT / 10 PM ET. The purchase will activate as a Steam key.