Mathematica: Getting part of a list, lithin a loop.

  • Context: Mathematica 
  • Thread starter Thread starter teroenza
  • Start date Start date
  • Tags Tags
    List Loop Mathematica
Click For Summary
SUMMARY

The discussion centers on an issue encountered while using Mathematica's Flatten function within a loop. The user successfully retrieves the fourth element of a flattened list when executed outside the loop. However, inside the loop, an error occurs indicating that the part specification exceeds the object's depth. The problem is identified as a missing semicolon after the Flatten function call, which is crucial for proper execution in Mathematica.

PREREQUISITES
  • Familiarity with Mathematica syntax and functions
  • Understanding of list manipulation in Mathematica
  • Knowledge of loop structures in programming
  • Basic debugging techniques in Mathematica
NEXT STEPS
  • Review Mathematica's documentation on the Flatten function
  • Learn about error handling in Mathematica
  • Explore list indexing and part specifications in depth
  • Investigate best practices for using loops in Mathematica
USEFUL FOR

Mathematica users, programmers working with list manipulations, and anyone interested in debugging loop-related issues in their code.

teroenza
Messages
190
Reaction score
5
When I use the code directly below, it works (indicated by the "Out:...").
Code:
tmp2 = Flatten[{33, {1, 2 + j, 6}, 55}];(*Out:{33,1,2+j,6,55} *)

tmp2[[4]]; (*Out: 6 *)

But when I use it inside a loop, it acts like the tmp2 list is not the correct size:
Code:
For[j = 0, j <= 5, j++,
tmp2 = Flatten[{33, {1, 2 + j, 6}, 55}]
   Print[tmp2[[4]]]
]

(*Out: Part::partd: Part specification tmp2[[4]] is longer than depth of object. >>*)

This is a minimal example of a larger piece, but I don't see why it's not working.
 
Physics news on Phys.org
It looks like you forgot a semicolon after the call to Flatten.
 
  • Like
Likes   Reactions: teroenza
Sigh. You are correct, thank you very much.
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
5K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 6 ·
Replies
6
Views
6K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K