Skip to content

Tag: lists

Java, printing arrays

As I keep forgetting, this post is to remind me that Java Java doesn’t have a pretty toString() for arrays objects, and it does for Lists.

[java]import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class ListsExample {
public static void main (String args[]) {
// as an array
String[] list1 = {"a","b","c"};
System.out.println(Arrays.toString(list1));

// as an List provided by Arrays
List<String> list2 = Arrays.asList("d", "e", "f");
System.out.println(list2);

// as an implementation of the interface List
// ArrayList (could also be LinkedList, Vector, etc)
List<String> list3 = new ArrayList<String>();
list3.add("g");
list3.add("h");
list3.add("i");
System.out.println(list3);
}
}
[/java]

The output is:

[a, b, c]
[d, e, f]
[g, h, i]

Python, flatten a list

Surprisingly python doesn’t have a shortcut for flatten a list (more generally a list of lists of lists of…).

I made a simple implementation that doesn’t use recursion and tries to be written clearly.

I get a element from a “notflat” list (a list that can have another lists on it). If a element is not a list we store in our flat list. If the element is still a list we deal with him later. The flat list always have only elements that are not a list.
To preserve the original order we reverse the elements at the end.