We can use the list() function to convert tuple to list in Python.
Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket.
tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
To convert a tuple of lists into an array, use the np. asarray() function and then flatten the array using the flatten() method to convert it into a one-dimensional array.
Convert tuple to list:
>>> t = ('my', 'name', 'is', 'mr', 'tuple')
>>> t
('my', 'name', 'is', 'mr', 'tuple')
>>> list(t)
['my', 'name', 'is', 'mr', 'tuple']
Convert list to tuple:
>>> l = ['my', 'name', 'is', 'mr', 'list']
>>> l
['my', 'name', 'is', 'mr', 'list']
>>> tuple(l)
('my', 'name', 'is', 'mr', 'list')
You have a tuple of tuples.
To convert every tuple to a list:
[list(i) for i in level] # list of lists
--- OR ---
map(list, level)
And after you are done editing, just convert them back:
tuple(tuple(i) for i in edited) # tuple of tuples
--- OR --- (Thanks @jamylak)
tuple(itertools.imap(tuple, edited))
You can also use a numpy array:
>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1]])
For manipulating:
if clicked[0] == 1:
x = (mousey + cameraY) // 60 # For readability
y = (mousex + cameraX) // 60 # For readability
a[x][y] = 1
You can have a list of lists. Convert your tuple of tuples to a list of lists using:
level1 = [list(row) for row in level1]
or
level1 = map(list, level1)
and modify them accordingly.
But a numpy array is cooler.
To convert tuples to list
(Commas were missing between the tuples in the given question, it was added to prevent error message)
Method 1:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1 = [list(row) for row in level1]
print(level1)
Method 2:
level1 = map(list,level1)
print(list(level1))
Method 1 took --- 0.0019991397857666016 seconds ---
Method 2 took --- 0.0010001659393310547 seconds ---
Why don't you try converting its type from a tuple to a list and vice versa.
level1 = (
(1,1,1,1,1,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,1,1,1,1,1))
print(level1)
level1 = list(level1)
print(level1)
level1 = tuple(level1)
print(level1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With