Advertisements

Iam struggling to understand why the first way works and the second throws error.

Suppose we have this array

```
interests =[(0,"Hadoop"),(0,"Big Data"),(0,"HBase"),(0,"Java"),(0,"Spark"),(0,"Storm"),(0,"Cassandra"),(1,"NoSQL",0),
(1,"MongoDB"),(1,"Cassandra"),(1,"HBase"),(1,"Postgres"),(2,"Python"),(2,"scikit-learn"),(2,"scipy"),(2,"numpy"),
(2,"statsmodels"),(2,"pandas"),(3,"R"),(3,"Python"),(3,"statistics"),(3,"regression"),(3,"probability"),
(4,"machine learning"),(4,"regression"),(4,"decision trees"),(4,"libsvm"),(5,"Python"),(5,"R"),(5,"Java"),
(5,"C++"),(5,"Haskell"),(5,"programming languages"),(6,"statistics"),(6,"probability"),(6,"mathematics"),
(6,"theory"),(7,"machine learning"),(7,"scikit-learn"),(7,"Mahoot"),(7,"neural networks"),(8,"neural networks"),
(8,"deep learning"),(8,"Big Data"),(8,"artificial intelligence"),(9,"Hadoop"),(9,"Java"),(9,"MapReduce"),
(9,"Big Data")]
```

1)I want to iterate over the tuple-elements of this list like this.

```
for x, y in interests:
print(x,y)
```

This works only for tuples with first element equals to 0 and then throws value error.

2)Below, this way works.

```
for interest in interests:
print(interest[0],interest[1])
```

3)And lastly this way below also gives the same result with the first way.

```
for interest in interests:
x,y = interest
print(x,y)
```

I cant imagine how i can unpack correct the values

### >Solution :

It’s only printing the first couple tuples(Until 0,"Cassandra") because the one right after it has 3 elements inside it – (1,"NoSQL",0), the for loop has only mentioned x,y (2)

You can use this instead –

```
interests =[(0,"Hadoop"),(0,"Big Data"),(0,"HBase"),(0,"Java"),(0,"Spark"),(0,"Storm"),(0,"Cassandra"),(1,"NoSQL",0),
(1,"MongoDB"),(1,"Cassandra"),(1,"HBase"),(1,"Postgres"),(2,"Python"),(2,"scikit-learn"),(2,"scipy"),(2,"numpy"),
(2,"statsmodels"),(2,"pandas"),(3,"R"),(3,"Python"),(3,"statistics"),(3,"regression"),(3,"probability"),
(4,"machine learning"),(4,"regression"),(4,"decision trees"),(4,"libsvm"),(5,"Python"),(5,"R"),(5,"Java"),
(5,"C++"),(5,"Haskell"),(5,"programming languages"),(6,"statistics"),(6,"probability"),(6,"mathematics"),
(6,"theory"),(7,"machine learning"),(7,"scikit-learn"),(7,"Mahoot"),(7,"neural networks"),(8,"neural networks"),
(8,"deep learning"),(8,"Big Data"),(8,"artificial intelligence"),(9,"Hadoop"),(9,"Java"),(9,"MapReduce"),
(9,"Big Data")]
for x,y,*a in interests:
print(x)
print(y)
```