list
as a variable name might get you into trouble caio, try to make it a habit to prefix (myVar, pVar etc) or proper case (ProperCaseExample) your variable names otherwise you might end up overwriting a keyword. Python is lax in its protection of keywords and will not even issue a warning if you do overwrite one. Most python keywords are all lower case, True
and False
being notable exceptions, therefore declaring your variable names in any case other than lower case reduces the risk of problems later. Consider this:
list # list is a keyword, python already knows what it is
<type 'list'>
list() # returns a new, empty list but could also convert a tuple into a list
[]
list = [1,2] # oops, we've just overwritten list with a value
list # now list is no longer <type 'list'> it's now [1,2]
[1, 2]
list() # as list has been overwritten you can no longer use it as before
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'list' object is not callable
Because you've overwritten the builtin object list
if you later decide to use list(myTuple)
to convert a tuple into a list, a handy approach as tuples are read only and if you want to change or remove values do so as a list object then convert back to a tuple. Now that list
is overwritten python is going to throw an exception and you will struggle for a very long time trying to find the error in syntax that checks out 100% with every reference and the problem could be hundreds of lines before.
Another option to append elements into a list that works for me is list += x
which works if x is a tuple or list. The addition assignment operator (+=
) also works for lists of more than one element:
myList = [1,2]
myList += [3,4]
myList is now [1, 2, 3, 4]
Append has a different behavior with lists:
myList = [1,2]
myList.append([3,4])
myList is now [1, 2, [3, 4]]
Which is probably not what was intended but is great if you know this quirk and are prepared for list or tuple items in your list.
In your code:
with arcpy.da.SearchCursor(teste, "ID_TALHAO") as cursor:
list = []
for x in cursor:
list += x
print(list)
sample = random.sample(list, 2)
print(sample)
or as a list comprehension:
list = [x[0] for x in arcpy.da.SearchCursor(teste, "ID_TALHAO")]
Note that the addition assignment is not valid here, you need to use indexing as Hornbydd indicates in his answer.
for x, in cursor:
or specify the index within the tuplelist.append(x[0])