top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between tuples and lists in Python?

+1 vote
524 views
What is the difference between tuples and lists in Python?
posted Sep 15, 2017 by Jdk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

List is similar to arrays in C but it can have items of different datatypes. Difference between list and tuple is that, Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.

answer Sep 27, 2017 by Afzal Labeeb
Similar Questions
+4 votes

I have a list of tuples where the number of rows in the list and the number of columns in tuples of the list will not be constant. i.e.

list = [(a1,b1, …z1), (a2,b2, …, z2),…. ,(am,bm, … , zm )]. It can be compared to the SQL results, as the number of columns change in the sql, the number of columns change in the list of tuples as well.

I have to iterate through each element of each tuple in the list, perform some checks on the value, convert it and return the modified values as a new list of tuples.

i.e.  list_value = [(‘name1’, 1234, ‘address1’ ), (‘name2’, 5678, ‘address2’), (‘name3’, 1011, ‘addre”ss3’)] 

I need to access each value to check if the value contains a double quote and enclose the string containing double quote with double quotes. The transformation should return

list_value = [(‘name1’, 1234, ‘address1’ ), (‘name2’, 5678, ‘address2’), (‘name3’, 1011, ‘”addre”ss3”’)] 

The simplest approach for me would be to do this:

mod_val = [transform(row) for row in list_value] 
def transform(row): 
   mod_list=[] 
   while index < len(row): 
...    if isinstance(row[index],basestring): 
...       if " in row[index]: 
...          mod_list.append("+row[index]+") 
...    else: 
...       mod_list.append(row[index]) 
...    index = index+1 
... return mod_list 

Is there a way to make the code concise using list comprehension?

+1 vote

I want to find the maximal number of elements contained in a nested dictionary, e.g.

data = {
 'violations':
 {
 'col1': {'err': [elem1, elem2, elem3]},
 'col2': {'err': [elem1, elem2]}
 }
 }

so to find the maximal number of elements in the lists for key 'err' in key 'col1' and 'col2'. Also key 'violations' may contain many keys (e.g. 'col1' , 'col2', 'col3' etc), so what's the best way to do this (using a loop)?

max = 0for col in data.violations:
 if max < len(data.violations.col.err):
 max = len(data.violations.col.err)
...