Python update object in list

Python – Updating object properties in list comprehension way

Is that possible, in Python, to update a list of objects in list comprehension or some similar way?
For example, I’d like to set property of all objects in the list:

result = [ object.name = "blah" for object in objects] 
result = map(object.name = "blah", objects) 

Could it be achieved without for-looping with property setting?

(Note: all above examples are intentionally wrong and provided only to express the idea)

Best Solution

Ultimately, assignment is a «Statement», not an «Expression», so it can’t be used in a lambda expression or list comprehension. You need a regular function to accomplish what you’re trying.

There is a builtin which will do it (returning a list of None ):

[setattr(obj,'name','blah') for obj in objects] 

But please don’t use it. Just use a loop. I doubt that you’ll notice any difference in efficiency and a loop is so much more clear.

If you really need a 1-liner (although I don’t see why):

for obj in objects: obj.name = "blah" 

I find that most people want to use list-comprehensions because someone told them that they are «fast». That’s correct, but only for creating a new list. Using a list comprehension for side-effects is unlikely to lead to any performance benefit and your code will suffer in terms of readability. Really, the most important reason to use a list comprehension instead of the equivalent loop with .append is because it is easier to read.

Python – How to check if a list is empty
if not a: print("List is empty") 

Using the implicit booleanness of the empty list is quite pythonic.

Python – Finding the index of an item in a list

Caveats follow

Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can’t remember the last time I used it in anger. It’s been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index follow. It is probably worth initially taking a look at the documentation for it:

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

Читайте также:  Fullscreen dialog android kotlin

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If your list is long, and you don’t know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999) , because the former only has to search 10 entries, while the latter searches a million:

>>> import timeit >>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000) 9.356267921015387 >>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000) 0.0004404920036904514 

Only returns the index of the first match to its argument

A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

>>> [1, 1].index(1) 0 >>> [i for i, e in enumerate([1, 2, 1]) if e == 1] [0, 2] >>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1) >>> next(g) 0 >>> next(g) 2 

Most places where I once would have used index , I now use a list comprehension or generator expression because they’re more generalizable. So if you’re considering reaching for index , take a look at these excellent Python features.

Throws if element not present in list

A call to index results in a ValueError if the item’s not present.

>>> [1, 1].index(2) Traceback (most recent call last): File "", line 1, in ValueError: 2 is not in list 

If the item might not be present in the list, you should either

  1. Check for it first with item in my_list (clean, readable approach), or
  2. Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.)
Related Question

Источник

How to update values in a List in Python?

In Python, lists are mutable. It means we can change the list’s contents by adding, updating, or removing elements from the list. In this article, we will discuss how to do update values of existing list elements in Python.

Updating existing element in the list

The list is an index-based sequential data structure. Therefore we can access list elements by their index position and change their values. Let’s understand by an example,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15]

Now we want to change the value of the 3rd element from 11 to 21.
We need to access the 3rd element from the list using square brackets and the index position of the element. Then assign a new value to it. Like this,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15] # Update value of 3rd element in list list_of_numbers[2] = 21 print(list_of_numbers)

Frequently Asked:

As indexing starts from 0 in list, so index position of third element in list is 2. We accessed the element at index position two and assigned a new value to it.

Читайте также:  Get set java горячие клавиши

Updating multiple elements in a list

You can select multiple items from a list using index range, i.e., start & end index positions. For example,

It returns a reference to the selected elements from the calling list object, and we can assign new values to these elements. Let’s see an example,

Suppose we have a list of numbers,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15]

Now we want to change the value of the first three elements to 10. For that we can select a range from list i.e., from index position 0 to 3 and assign value 10 to it,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15] # change the value of the first three elements to 10. list_of_numbers[0:3] = [10, 10, 10] print(list_of_numbers)

It updated the value of the first three elements in the list.

Today we learned how to update values of single or multiple elements in a list.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

Читайте также:  Php sql две таблицы

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

How to Modify an Item Within a List in Python

Data to Fish

If so, you’ll see the steps to accomplish this goal using a simple example.

Steps to Modify an Item Within a List in Python

Step 1: Create a List

To start, create a list in Python. For demonstration purposes, the following list of names will be created:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] print(Names)

Run the code in Python, and you’ll get this list:

['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] 

Step 2: Modify an Item within the list

You can modify an item within a list in Python by referring to the item’s index.

What does it mean an “item’s index”?

Each item within a list has an index number associated with that item (starting from zero). So the first item has an index of 0, the second item has an index of 1, the third item has an index of 2, and so on.

  • The first item in the list is ‘Jon.’ This item has an index of 0
  • ‘Bill’ has an index of 1
  • ‘Maria’ has an index of 2
  • ‘Jenny’ has an index of 3
  • ‘Jack’ has an index of 4

Let’s say that you want to change the third item in the list from ‘Maria’ to ‘Mona.’ In that case, the third item in the list has an index of 2.

You can then use this template to modify an item within a list in Python:

ListName[Index of the item to be modified] = New value for the item

And for our example, you’ll need to add this syntax:

So the complete Python code to change the third item from Maria to Mona is:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] #modify Names[2] = 'Mona' print(Names)

When you run the code, you’ll get the modified list with the new name:

Change Multiple Items Within a List

What if you want to change multiple items within your list?

For example, what if you want to change the last 3 names in the original list:

You can then specify the range of index values where the changes are required. For our example, the range of index values where changes are required is 2:5. So here is the code to change the last 3 names in the list:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] #modify Names[2:5] = 'Mona','Lina','Mark' print(Names)

You’ll now see the updated list with the 3 new names:

You can get the same same results by using Names[-3:] as below:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] #modify Names[-3:] = 'Mona','Lina','Mark' print(Names)

And as before, you’ll now see the updated list with the 3 new names:

Источник

Оцените статью